From: "David A. Black" Date: 2009-07-08T22:28:25+09:00 Subject: Re: Symbol#to_proc with arguments Hi -- On Wed, 8 Jul 2009, James Coglan wrote: > 2009/7/8 David A. Black > >> Hi -- >> >> >> On Wed, 8 Jul 2009, James Coglan wrote: >> >>> You could rewrite Symbol#to_proc to take arguments, and call #to_proc >>> explicitly when calling #collect. >>> >>> class Symbol >>> def to_proc(*args) >>> lambda { |o| o.__send__(self, *args) } >>> end >>> end >>> >>> %w[apple banana peach plum pear].collect &:split.to_proc('l') >>> #=> [["app", "e"], ["banana"], ["peach"], ["p", "um"], ["pear"]] >>> >> >> That's going to be incomprehensible, except by guesswork, to anyone >> who doesn't know that you've modified Symbol. It also undoes whatever >> benefit you might get from the &obj idiom automatically calling >> #to_proc. I'd just do: >> >> array.map {|e| e.split('l') } > > > I wouldn't say it's incomprehensible since it maintains the existing > semantics of Symbol#to_proc. I don't think that's right. The existing semantics don't include any arguments. So my reaction would be: isn't that going to raise an exception? Then I'd have to figure out that you'd probably overridden then method. > The explicit block version is shorter though, > and will likely perform better. > > No real reason to second-guess Ruby on this. If you really want to >> modify Symbol, creating an entirely new method would probably be >> better: >> >> array.map(&:split.to_argument_accepting_proc('l')) > > > The real problem here is that a Symbol contains a single piece of > information, whereas we want to build a Proc from several pieces of > information. Just rename your override of #to_proc to #to_proc_with_args (or whatever). It will still work the same. (You're dispensing with the automatic calling of #to_proc anyway.) > So, an alternative: > > class Array > def to_proc > lambda { |o| o.__send__(first, *self[1..-1]) } That doesn't differ from __send__(*self), does it? David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Now available: The Well-Grounded Rubyist (http://manning.com/black2) Training! Intro to Ruby, with Black & Kastner, September 14-17 (More info: http://rubyurl.com/vmzN)