Quantcast
Channel: Schneems
Viewing all articles
Browse latest Browse all 45

TIL: Symbol to Proc Trick not needed in Ruby Inject/Reduce 2.0.0

$
0
0

If you’ve been using Ruby for some time no doubt you’ve done something like this to sum up an array of integers:

[1,2,3].inject(&:+)
# => 6

This works because Ruby will take the symbol :+ and turn it into a Proc, or anonymous function since we’re putting the & in front of it (similar to how you would tell ruby you expect a block argument by using a &). The code above essentially boils down to:

[1,2,3].inject {|x,y| x + y}
# => 6

Today I learned that you don’t need to convert your symbol into a proc to do this, you can just pass in a symbol.

[1,2,3].inject(:+)
# => 6

I like this version much better, hope you do to. I found out about this from watching Avdi code on his Ruby Tapas. If you know when this was added, or the source that makes this possible let me know.

Even old dogs can learn new tricks.

Update

This behavior is localized to only inject/reduce methods. For instance you cannot do this.

["a", "b"].map(:upcase)
ArgumentError: wrong number of arguments (1 for 0)
    from (irb):3:in `map'
    from (irb):3
    from /Users/schneems/.rbenv/versions/2.0.0-p247/bin/irb:12:in

You must:

["a", "b"].map(&:upcase)
["A", "B"]

Update 2

This feature has been around for a long time https://eval.in/67239 thanks @charliesome.


Viewing all articles
Browse latest Browse all 45

Latest Images

Trending Articles





Latest Images