to_proc
Posted by Scott Laird Thu, 03 Nov 2005 23:02:49 GMT
Dave Thomas just pointed out a great little hack from the Ruby Extensions Project. They added this little snippet to Object:
def to_proc
proc { |obj, *args| obj.send(self, *args) }
endand now instead of writing this:
result = names.map {|name| name.upcase}you can write this:
result = names.map(&:upcase)The “wave this method over all objects in a collection” idiom is very common in Ruby, and Ruby’s native block syntax isn’t too bad for this use, but it’s not as clean as Python’s list comprehension syntax would be:
result = [n.upper() for n in names]With the to_proc hack in place, Ruby’s code is a bit cleaner, at the cost of using a non-standard extension to the language. Personally, I’d prefer to see map extended to take an optional symbol, then we could ditch the ugly & when we’re using a single method with no parameters.
