How does “(1..4).inject(&:+)” work in Ruby

后端 未结 1 1125
孤街浪徒
孤街浪徒 2020-11-27 21:43

I find this code in Ruby to be pretty intriguing

(1..4).inject(&:+)

Ok, I know what inject does, and I know this code is b

相关标签:
1条回答
  • 2020-11-27 22:23

    From Ruby documentation:

    If you specify a symbol instead, then each element in the collection will be passed to the named method of memo

    So, specifying a symbol is equivalent to passing the following block: {|memo, a| memo.send(sym, a)}

    If you do not explicitly specify an initial value for memo, then uses the first element of collection is used as the initial value of memo.

    So, there is no magic, Ruby simply takes the first element as the initial value and starts injecting from the second element. You can check it by writing [].inject(:+): it returns nil as opposed to [].inject(0, :+) which returns 0.

    Edit: I didn't notice the ampersand. You don't need it, inject will work with a symbol. But if you do write it, the symbol is converted to block, it can be useful with other methods

    0 讨论(0)
提交回复
热议问题