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.
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.
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")}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With