Proc

suggest change
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       # prints the Proc; this does not call it
puts its_a.call  # prints: beautiful day
puts its_a[1, 2]
# prints:
# 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. puts on the proc itself prints the proc. Call it with call or []. [] here is a call, and the puts inside the proc runs before the outer puts prints the return value.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents