[ ruby ] lambda expression with array/range/file

map

[1, 2, 3].map { |item| item + 10 } == [11, 12, 13]
[1, 2, 3].collect { |item| item + 10 } == [11, 12, 13]

select

[1, 2, 3, 4, 5, 6].select { |item| (item % 2) == 0 } == [2, 4, 6]
[1, 2, 3, 4, 5, 6].find_all { |item| (item % 2) == 0 } == [2, 4, 6]

inject

[2, 3, 4].inject(0) { |sum, item| sum + item } == 9

 

[2, 3, 4].inject(1) { |product, item| product * item }

find

["Jim", "Bill", "Clarence", "Doug", "Eli"].find { |item| item.size > 4 } == "Clarence"

ref : http://rubykoans.com/

lambda

add_one = lambda { |n| n + 1 }
11 == add_one.call(10)
# Alternative calling syntax
11 == add_one[10]
Advertisements

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