Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to get a value from a block in Ruby?

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?

like image 295
Laura Gyre Avatar asked Oct 22 '14 20:10

Laura Gyre


2 Answers

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
like image 159
Jordan Running Avatar answered Sep 25 '22 01:09

Jordan Running


Try:

if block_given?
   if yield self[x]
      # Do something....
   end
end
like image 43
tomsoft Avatar answered Sep 22 '22 01:09

tomsoft