From: Arturo Garcia Date: 2010-11-26T23:11:45+09:00 Subject: Re: Newbie: two cool discoveries the "&" is a shortcut to "to_proc" class Symbol def to_proc lambda { |x| x.__send__(self) } end end So in theory, you could use to send *any* message ( Ruby 1.9* btw ) On Friday 26 November 2010 14:00:15 Diego Virasoro wrote: > Hi all, > I just wanted to share a couple of things I've found out lately. I > imagine they are well known to the experts here, but I thought maybe > there are other newbies out there that could benefit from it too. > > 1) Using proc in the case statement: > > I find the case statement particularly elegant: especially when > there's a long list of choices I much prefer it to using if... > elsif... else... end. That said the latter offers a lot more > flexibility. Still a lot can be accomplished by using procs. For > example: > > case val > when Hash > ... > when lambda{|x| x.respond_to?(:to_ary) && x.length>1} > ... > end > > The block takes the case argument and its output (generally true or > false...) is used to decide if the branch should be run or not. > > 2) Passing a block to map or similar methods. > > Say you have an array of numbers, and you want to invoke #abs for each > number. Rather than: > x = [1,-2,3,-4,5] > x.map{|x| x.abs} > > you can use: > x = [1,-2,3,-4,5] > x.map(&:abs) > > It may not seem much in this instance, but I found it a lot cleaner in > some cases, especially when there is a long chain of methods. > > Hope that helped _someone_ :) > > Diego