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

I used if yield self[x] to evaluate whether the block returns true or false. Do I need to make a block optional, and I see yield if block_given? . How to combine these two lines?

+7
ruby block optional
source share
3 answers

Have you tried this?

 if block_given? && yield(self[x]) # ... end 

This condition will always fail if no blocks are specified, i.e. anything that is in place of # ... will not be evaluated. If you want the condition to be successful if no blocks are specified, do this instead:

 if !block_given? || yield(self[x]) # ... end 

Or this, although it seems harder to read to me:

 unless block_given? && !yield(self[x]) # ... end 
+7
source share

Try:

 if block_given? if yield self[x] # Do something.... end end 
+3
source share

You can add a condition to the entire if block:

 if yield self[x] # do something... end if block_given? 
0
source share

All Articles