Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return true/false in a block in ruby

Tags:

ruby

I'm doing something like this:

myarray.delete_if{ |x|
   #some code
   case x
   when "something"
       return true
   when "something else"
       return false
   end

The "return" statement seems wrong, and I can't figure out the right syntax, I understand the simplistic form of: myarray.delete_if{ |x| x == y }, but not when my desire to return true/false is more procedural as in the case statement example.

like image 303
David Parks Avatar asked Sep 13 '26 19:09

David Parks


2 Answers

Just remove return. In Ruby, the last value evaluated is used as return value.

myarray = ["something", "something else", "something"]
myarray.delete_if { |x|
  #some code
  case x
  when "something"
    true
  when "something else"
    false
  end
}
myarray # => ["something else"]

You can use next if you want to be explicit.

like image 96
falsetru Avatar answered Sep 16 '26 12:09

falsetru


You do not need to particularly condition the false cases. They can be nil by default if you do not condition them.

myarray.delete_if do |x|
  ...
  case x
  when "something" then true
  end
end

or even better:

myarray.delete_if do |x|
  ...
  "something" === x
end

I do not know what you have in the ... part, but if you just want to remove a certain element from an array, you can do:

myarray.delete("something")

and if you want to get back the receiver, then:

myarray.tap{|a| a.delete("something")}
like image 39
sawa Avatar answered Sep 16 '26 12:09

sawa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!