Page 1 of 1

ruby binary operators for arrays

Posted: Sun Jun 29, 2014 1:31 pm
by tester
What are the ruby binary operators for arrays?

Like OR:

1
0
1
0

with

1
1
0
0

gives

1
1
1
0

Re: ruby binary operators for arrays

Posted: Sun Jun 29, 2014 5:22 pm
by trogluddite
Hi tester,
Good question - that works a little bit strangely in Ruby because it doesn't represent true and false the same way that 'green' does.

In 'green', zero = false, any other number = true.
In Ruby, 'nil' or 'false' = false, anything else = true (i.e. the number zero is also a 'true' value)

For what you want to do, though, using ones and zeros in an Integer Array is probably the best way - but you will have to be sure to use the 'bitwise' operators ('|' for OR, '&' for AND - single character) rather than the usual boolean ones ('||' for OR, '&&' for AND - two characters).

To do what you want, you'll need to use the 'zipping' technique, similar so your previous number and String code - something like this...

Code: Select all

output 0, @array1.zip(@array2).map{|a, b|  a | b}   # OR version
output 0, @array1.zip(@array2).map{|a, b|  a & b}  # AND version
output 0, @array1.zip(@array2).map{|a, b|  a ^ b}  # XOR version


Note that when using Integers this way, you won't be able to use the NOT operator ('!') - you'll need to use "(1 - x)" to turn ones into zeros and vice-versa.

Re: ruby binary operators for arrays

Posted: Sun Jun 29, 2014 6:24 pm
by tester
Ok, thanks.

So the not will be something like this?

Code: Select all

output 0, @a.zip(@a).map{|a, b|  1-a}   # NOT version

This one works, but I guess it should be simpler :mrgreen:

Re: ruby binary operators for arrays

Posted: Sun Jun 29, 2014 6:41 pm
by trogluddite
For NOT, just...

Code: Select all

@a.map{|a| 1 - a}

As NOT takes only one argument, there's no need to zip a copy of the array in this case.