Blocks, Procs, Lambdas

Block

3.times { puts “Ruby is fun!” }

Proc

say_hello = Proc.new { |name| puts “Hello, #{name}” }
say_hello.call(“Sara”)

Lambda

square = -> (x) { x * x }
puts square.call(5)
Block → Small piece of code in {} or do…end.

Proc → Stored block that can be reused.

Lambda → Like Proc but stricter with arguments.

Output:


Ruby is fun!
Ruby is fun!
Ruby is fun!
Hello, Sara
25

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *