Logic operators in Ruby

Moin Moin,

sometimes it’s really helpful to use a REPL to make things clear while coding. So you could use the awesome http://repl.it/ Ruby shell or simply open your terminal and use irb or pry. I did it today with my colleague Jan to remember who logical operators work for Ruby.

1. What is the result when I use && for two arrays?

[1] pry(main)> [1,2] && [3,4]
=> [3, 4]

The reason is, that here you check if both expressions are true. Ruby checks if the first expression is true and then checks if the second is also true. If yes, the last checked expression is returned. If you would examine another array as the last one (e.g. [5,6]), this one would be returned. Obviously if any of the expressions would be nil, nil would be the result.

2. What is the result when I use || for two arrays?

[2] pry(main)> [1,2] || [3,4]
=> [1, 2]

Here the first result is returned because the whole expression is returning true if at least one expression is true. If the first expression would be nil, the second would be returned.

3. What is the result when I use & for two arrays?

[3] pry(main)> [1,2] & [3,4]
=> []

It’s an empty array because the logic AND is checking, if one or more values of the array (in this case) are present in both arrays. So the next example shows that:

[4] pry(main)> [1,2] & [2,3,4]
=> [2]

Got it? Just think of the possibilities you have with that small size of code. For example you could use this operation to find all the unique values which are present in the first array AND the second array:

[5] pry(main)> [1,2,2] & [3,3,2,2,4]
=> [2]

[6] pry(main)> [1,2,2,3] & [3,3,2,2,4]
=> [2, 3]

4. What is the result when I use | for two arrays?

[7] pry(main)> [1,2] | [3,4]
=> [1, 2, 3, 4]

The logic OR is returning all results from expression one and two. The result in this case (!) is the same like you would add both arrays but for sure these are two different things!

[8] pry(main)> [1,2] + [3,4]
=> [1, 2, 3, 4]

And here is a real nice thing when using logic OR. Look at this:

[9] pry(main)> [1,2,2] | [3,3,4]
=> [1, 2, 3, 4]

Nice and obvious. The logic OR is returning all unique values from array one and two. Now the difference to the + operator is clear:

[10] pry(main)> [1,2,2] + [3,3,4]
=> [1, 2, 2, 3, 3, 4]

Have fun!

Cheers

Andy

Published: October 17 2012