I have been using if yield self[x]
to evaluate whether a block returns true or false.
I need to make the block optional, and I see suggestions to do yield if block_given?
.
How can I combine these two lines?
Have you tried this?
if block_given? && yield(self[x])
# ...
end
This condition will always fail when no block is given, i.e. whatever is in place of # ...
won't be evaluated. If you want the condition to succeed if no block is given, do this instead:
if !block_given? || yield(self[x])
# ...
end
Or this, although I think it's harder to read:
unless block_given? && !yield(self[x])
# ...
end
Try:
if block_given?
if yield self[x]
# Do something....
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With