--0016e65aedd6461a4c047716e15e
Content-Type: text/plain; charset=ISO-8859-1
Hi rubyists,
I was just wondering why,
(1..4).inject(&:+) # 10
works ? (in Ruby 1.9.2)
I understand easily these:
(1..4).inject { |s, e| s + e } # 10
(1..4).inject(:+) # 10
I suppose it's calling :+.to_proc # #<Proc:0x2f52d8>
irb> def a(&b); b; end
irb> a(&:+)
#<Proc:0x2f52d8>
irb> :+.to_proc
#<Proc:0x2f52d8>
irb> p (&:+)
#<Proc:0x2f52d8>
irb> p.arity
-1
irb> p.call(1,2)
3
irb> p.call(1)
ArgumentError: wrong number of arguments(0 for 1)
...
irb> p.call(1,2,3)
ArgumentError: wrong number of arguments(2 for 1)
...
irb> p.call
ArgumentError: no receiver given
Well, that's strange: arity 1, so normally only optional arguments. And
it expects 1 argument but want 2 ?
"no receiver given" : That means it knows it has a argument to act on like
a.+(b). How come ?
Would &:+ knows it need some object to act with "+"(o) ?
Have a nice day
--0016e65aedd6461a4c047716e15e--