Method Calls in Ruby – 2 (map)

A little more on meta-programming. “map(&:to_i)” sounds neat. It would be useful when handling string inputs.

p ["10", "20"].map(&:to_i)
 # => [10, 20]

proc1 = :to_i.to_proc
p ["10", "20"].map(&proc1)
# => [10, 20]

proc2 = Proc.new { |x| x.to_i }
p ["10", "20"].map(&proc2)
 # => [10, 20]

proc3 = Proc.new { |x| x.send(:to_i) }
p ["10", "20"].map(&proc3)
 # => [10, 20]

p ["10", "20"].map(&method(:Integer))
 # => [10, 20]
Advertisements

Posted on January 27, 2013, in Ruby. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: