DEV Community

Discussion on: Post an Elegant Code Snippet You Love.

Collapse
 
ben profile image
Ben Halpern

I think pulling from arrays with some filters in Ruby is nice, such as

[1, 2, 3, 4, 2, 3, 1, 3, 4, 5].uniq.compact.select(&:even?)
Enter fullscreen mode Exit fullscreen mode

uniq removes dupes and compact removes nil and .select(&:even?) will limit the output to even numbers.

Collapse
 
baenencalin profile image
Calin Baenen • Edited

what is the syntax &:even??

Collapse
 
edwardloveall profile image
Edward Loveall • Edited

I've heard it called a "symbol to proc" or "symbol proc" and it's short for this:

.select { |foo| foo.even? }
# same as 
.select(&:even?)
Enter fullscreen mode Exit fullscreen mode

It's calling the method even? on each number passed in. Behind the scenes it creates a proc and then passes in each number. Here are the ruby docs for Symbol#to_proc and here's a pretty decent break down of symbol to proc.