0

Ruby - Playing with lambdas

What does this code do? def say(*args) args[0].call end def something if block_given? return yield end lambda {puts "Hi."} end say something{ lambda{puts "Bye."} }

26th Jun 2020, 11:57 AM
Paolo De Nictolis
Paolo De Nictolis - avatar
1 Odpowiedź
+ 4
As I understand it, something() checks if a code block is given as a parameter to the function. If so, it yields it. Now, as say method is defined, it calls its first argument. Since it's something and it *has* the block given, it yields it. The block happens to be a lambda function which puts "Bye." So "Bye." is being put.
26th Jun 2020, 12:23 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar