0

I'm trying to write some Ruby code that will return a value from a block that is passed to a function. I don't want the block to exit early, I just want to avoid writing too many if statements in order to implicitly return the value.

How can I rewrite this to return the value early?

This works:

def my_method
  my_array.delete_if do |item|
    if item.removed?
      true
    elsif item == 'something else'
      true
    else
      false
    end
  end
end

This won't work because you can't call return in a block:

def my_method
  my_array.delete_if do |item|
    return true if item.removed?
    return true if item == 'something else'

    # ...
  end
end
Andrew
  • 227,796
  • 193
  • 515
  • 708
  • Is the intent to remove items from the array if either (a) calling `#removed?` on the item returns true or (b) the item is equivalent to `something else`? Are you able to add a method to the class that `item` belongs to? – moveson Nov 02 '16 at 18:07
  • The code in the example was just to demonstrate the scenario, I am actually working with an array of strings, not objects. I'm really just trying to figure out how to return the value without exiting the block. – Andrew Nov 02 '16 at 18:14
  • [This answer](http://stackoverflow.com/a/11678342/479863) to the duplicate seems to be what you're looking for. – mu is too short Nov 02 '16 at 18:25

0 Answers0