Thread: Ruby Snippets
View Single Post
Old Jul 8th, 2006, 7:40 PM   #28
Jessehk
The Oblivious One
 
Jessehk's Avatar
 
Join Date: May 2005
Location: Ontario, Canada
Posts: 644
Rep Power: 4 Jessehk is on a distinguished road
This trick is just cool.

Imagine being able to do things like this:

["Joe", "Sally", "Phil"].map(&:upcase) #=> ["JOE", "SALLY", "PHIL"]

With this snippet, you can. I did not think of this.

class Symbol
    def to_proc
        lambda { |obj, *args| obj.send(self, *args) }
    end
end

Example usage:
require 'jesse_symbol' #where new code is stored

class Integer
    def square
        self * self
    end
end

p (1..10).map(&:square)

#or even
p (1..10).inject(&:+) #sum
p (1..10).inject(&:*) #product

Full explanation: http://blogs.pragprog.com/cgi-bin/pr...by/ToProc.rdoc
__________________
Dr. Zoidberg: [ecstatic] I'm going to a movie... with FRIENDS!
Jessehk is offline   Reply With Quote