简体   繁体   中英

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?

Have you tried this?

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

This condition will always fail when no block is given, ie 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

You can append a condition to the entire if block:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM