Closures and Method Objects
Blocks and lambdas capture the variables around them. method(:name) turns a method into an object, and & converts it back to a block.
Example
def make_counter
c = 0
-> { c += 1 }
end
next_n = make_counter
next_n.call; puts next_n.call
puts [1, 2, 3].map(&10.method(:+)).inspect
puts %w[a b].map(&:upcase).inspectResult
2 [11, 12, 13] ["A", "B"]
Exercise
Method as an object.
5.(:+)
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.