Ruby Language Blocks and Procs and Lambdas Proc

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

def call_the_block(&calling); calling.call; end

its_a = proc do |*args|
  puts "It's a..." unless args.empty?
  "beautiful day"
end

puts its_a       #=> "beautiful day"
puts its_a.call  #=> "beautiful day"
puts its_a[1, 2] #=> "It's a..." "beautiful day"

We've copied the method call_the_block from the last example. Here, you can see that a proc is made by calling the proc method with a block. You can also see that blocks, like methods, have implicit returns, which means that procs (and lambdas) do too. In the definition of its_a, you can see that blocks can take splat arguments as well as normal ones; they're also capable of taking default arguments, but I couldn't think of a way to work that in. Lastly, you can see that it's possible to use multiple syntaxes to call a method -- either the call method, or the [] operator.



Got any Ruby Language Question?