Question

I'm not much of a Ruby person, so I might just miss something really basic here, but I couldn't figure it out yet: Say I have an array that contains any amount of 2 element arrays of integers. I would like to bitwise xor every set of two integers.
I currently use the really obvious

l.map {|n1, n2| n1 ^ n2}

My first though was to do something along the lines of l.map &:^, though. Obviously this is not possible, because there is no such thing as Array#^ and the resulting proc doesn't do parameter unpacking. Is there a nice way to do this using symbol to proc logic or am I stuck with the functional, but undoubtedly less elegant solution I currently use?

Regards,
Copper Phosphate

Was it helpful?

Solution

There is a way to do this using Symbol#to_proc, but it won't be any nicer than the (just fine) solution you already have, because it involves defining Array#^.

class Array
  def ^
    raise("Not a two-element array") unless (self.length == 2)
    raise("Array contains non-numeric values") unless (self.all? {|n| Integer === n })

    return self[0] ^ self[1]
  end
end

l.map(&:^)

OTHER TIPS

I'm afraid (?) that what you've already found the simplest way to write it.

There are ways to use Symbol#to_proc, but they are not as nice:

arr = [[1, 2], [2, 5], [23, 100], [5, 1], [4, 10]]

arr.map { |a, b| a ^ b }
# => [3, 7, 115, 4, 14]


arr.map { |pair| pair.reduce(&:^) }
#=> [3, 7, 115, 4, 14] 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top