the12 - 1 year ago 90
Ruby Question

# Why does Ruby require or operators for find_all method when searching multiple things?

Given the following code:

Why does Ruby require the or operator when searching for multiple things using the

`find_all`
method? I.e.:

``````x = [1,2,3,4,5]

variable = x.find_all do |x|
x.even?||x.odd?
end
puts variable
``````

I am trying figure out whether each number within the array is either even or odd. At the end, eventually putting the result of
`variable`
, if it is either of those two.

If you try to write the conditions you want find sequentially, it does not work:

``````variable = x.find_all do |x|
x.even?
x.odd?
end
``````

I am curious to know why that the first example works and the second one does not. The second equation, in my head I'm thinking you are simply listing them sequentially, trying to figure out whether x is even, THEN figure out whether x is odd. Unsure why it is not working. Can someone explain why or operators must be used as opposed to listing methods sequentially, when trying to search for multiple conditions?

Ruby has an implicit return where the last executed line in a method or a block will be the line that is returned. With this in mind

``````variable = a.find_all do |x|
x.even?
x.odd?
end
``````

Will only regard the line `x.odd?` when it comes to keeping that. You could do it without an or operator like this

``````variable = a.find_all do |x|
if x.even?
true
else
x.odd?
end
end
``````

For this if `x.even?` is true, then `true` will be returned as that is the last line of code run inside the block. If `x.even?` is false, then `x.odd?` will be returned as that is the last line of code run inside the block. If you are trying to check for multiple conditions using `||` is efficient but you can also do something like this.

Let's say I have the array `a = ['dog', 2, 3.4, 'PIZZA', false, nil]`. Let's say that I want all lowercase strings, all integers, and all nil values. I can do this

``````a.find_all do |i|
if i.is_a? String
i == i.downcase
elsif i.is_a? Numeric
i == i.to_i
else
i.nil?
end
end
``````

This would return `['dog', 2, nil]`.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download