"if yield" same as "yield if block evaluates to true"?
ruby
Solution
This might be helpful.
def event(name)
val = yield
puts val.inspect
puts "ALERT: #{name}" if val == "donald"
end
event "an event that always happens" do
"donald"
end
event "an event that never happens" do
"duck"
end
prints
"donald"
ALERT: an event that always happens
"duck"
Basically the return value of yield is whatever gets evaluated last in the block. And that is what is being used as a criteria in the if statement.
Problem
If I run the tests below on this code, it returns ``` ALERT: an event that always happens ``` I expected it to also put ``` ALERT: an event that never happens ``` but it didn't. I assume the reason for the difference is the 'true' and 'false' in the respective tests, but I don't see why 'true' or 'false' make a difference in this case. The method 'event' says ``` puts "ALERT: #{name}" if yield ``` If the result of the tests is explained by the fact that 'true' equals 'yield' in this context, whereas 'false' doesn't, how does 'false' negate 'yield'? Question: Does 'if yield' mean 'yield if the block evaluates to true'? code ``` def event(name) puts "ALERT: #{name}" if yield end Dir.glob('*events.rb').each {|file| load file } ``` tests ``` event "an event that always happens" do true end event "an event that never happens" do false end ``` Output ``` ALERT: an event that always happens ```