Select method with args separated by double-pipes only checking first element... Alternative?

StackOverflow https://stackoverflow.com/questions/20572900

Pregunta

I have a bit of broken legacy code I have to fix. Its purpose was to take a large array and return elements that have a particular sector number.

Here's a simplified version of the code in the app. Goal: return any instance of 1 or 3 in array:

array = [1,1,2,2,3,3].select{|num| num == (1 || 3) }

But the return value is simply #=> [1, 1] when the desired return was #=> [1, 1, 3, 3]

Basically, what I'm looking for is the Ruby equivalent to the following SQL query:

SELECT num FROM array
WHERE num IN (1, 3);

Ruby 1.8.7, Rails 2.3.15

¿Fue útil?

Solución

Do as below to meet your need :

array = [1,1,2,2,3,3]
array.select{|num| [1,3].include? num }
# => [1, 1, 3, 3]

See why you got only [1,1].

1 || 3 # => 1

1 || 3 will always returns 1, thus num == 1 is evaluated as true when select is passing only 1. As a result you got [1,1].

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top