Question

I have the following code

def assert
  raise "Assertion failed!" unless yield
end

swear = "shoot"
assert { swear == "shoot" }
assert { swear == "snot head" }

There are two things going on here that I need a bit more explanation on what they are exactly doing.

  1. What exactly do the curly brackets and the stuff inside do. I have a general sense that it somehow passes in the comparisons, but what can/can't be put in there. I tried replacing with a puts statement and it seems to ignor. What does it do?

  2. What does yield do? does it execute what is in the curly brackets and does it only work on true/false?

Was it helpful?

Solution

  1. Curly brackets are blocks in Ruby.
  2. The yield keyword will execute the block which passed to methods.
  3. All Ruby methods accept blocks implicitly.

assert { swear == "shoot" } actually sends the block to assert method. Since the evaluation of the block is true, there is no exception raised. While { swear == "snot head" } is false, assert method raises an exception.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top