From: Benoit Daloze Date: 2009-10-30T19:48:48+09:00 Subject: Re: Why (1..4).inject(&:+) works ? --0016e65bcd34a2499a047724c597 Content-Type: text/plain; charset=ISO-8859-1 In fact, I knew about about the 1.8 implementations. I just forgot about it. Thank to have cleared my ideas. The current implementation looks like (of course it must be in C): class Symbol def to_proc @to_proc ||= Proc.new { |*args| args.shift.send(self, *args) } end end 2009/10/30 Rick DeNatale > On Thu, Oct 29, 2009 at 2:14 PM, Benoit Daloze wrote: > > 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 #=> # > > > > irb> def a(&b); b; end > > irb> a(&:+) > > => # > > irb> :+.to_proc > > => # > > > > irb> p = a(&:+) > > => # > > 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) ? > > irb(main):001:0> 1.send(:+) > ArgumentError: wrong number of arguments(0 for 1) > from (irb):1:in `+' > from (irb):1 > from /Users/rick/.rvm/ruby-1.9.1-p243/bin/irb:12:in `
' > irb(main):002:0> 1.send(:+, 2) > => 3 > irb(main):003:0> 1.send(:+, 2, 3) > ArgumentError: wrong number of arguments(2 for 1) > from (irb):3:in `+' > from (irb):3 > from /Users/rick/.rvm/ruby-1.9.1-p243/bin/irb:12:in `
' > > > -- > Rick DeNatale > > Blog: http://talklikeaduck.denhaven2.com/ > Twitter: http://twitter.com/RickDeNatale > WWR: http://www.workingwithrails.com/person/9021-rick-denatale > LinkedIn: http://www.linkedin.com/in/rickdenatale > > --0016e65bcd34a2499a047724c597--