- Every function can accept a block.
Kernel.block_given?
will tell you if a block was passed.
def test
a = 42
yield(a) if block_given?
end
To assign the block to an argument, you add an ampersand (&) in front of the last argument of your function. This will affect performance.You can call the block inside the function using yield
or Proc.call
like this:
def test(&block)
a = 42
yield(a) # or block.call(a,b)
end
yield
calls and passes the arguments to the block.block.arity
will tell you the number of arguments a block can accept If you have a recursive function accepting a block, you can pass the block to it using '&'.
def recursive_function(&block)
# Do stuff
recursive_function(&block)
# pass to other functions accepting blocks
10.times &block # will run block 10 times
end
If you use the return keyword inside a block, it will return the value and exit the function binded to the block, which is the one that created it.
def bl(&block)
yield
end
def test
bl { return }
puts "Hello" # this will not be executed.
end
You can use break
to return a value inside a block and stop iterating.
def bl(&block)
(0..10).each &block
end
def test
# This block will stop iterating at 5 and return true.
bl { |x| (break true) if (x == 5); false }
end