[ next ] [ prev ] [ contents ] [ up to Understanding Blocks ] Using Ruby

Yielding to Blocks

def three_times(arg)
  yield(arg)
  yield(arg)
  yield(arg)
end

three_times("x") { |val| puts val }
three_times(22) do |thing|
  puts "Got #{thing}"
end

Output

x
x
x
Got 22
Got 22
Got 22

  • Blocks that directly follow a method call are implicitly passed to the method.

  • The method may call the proc by invoking yield and passing any arguments.

  • You can test for the presence of a block using block_given?.
    • yield(arg) if block_given?

  • The block may be explicitly passed using the & operator.

def three_times(arg, &block)
  block.call(arg)
  block.call(arg)
  block.call(arg)
end



[ next ] [ prev ] [ contents ] [ up to Understanding Blocks ] Copyright 2003 by Jim Weirich.
Some Rights Reserved