0

Suppose I have an array [1,2,3,4], and I want to do 1 | 2 | 3 | 4 in Ruby language

How to write it faster?

Actually, I just read an article about bitmask at CoderWall and I wonder when the settings have many options, such as 10 or 15, I think write (1 << 1 | 1 << 2 | 1 << 3 ... | 1 << 15).to_s(2) is too long.

Is there any way to write it shorter?

eugen
  • 8,916
  • 11
  • 57
  • 65
yeuem1vannam
  • 957
  • 1
  • 7
  • 15

1 Answers1

7

How about:

[1,2,3,4].inject(:|)

To create a bitmask I would do:

[1,2,3,4].map(&1.method(:<<)).inject(0, :|)

If you don't want to iterate twice, just add .lazy after array:

[1,2,3,4].lazy.map(&1.method(:<<)).inject(:|)
BroiSatse
  • 44,031
  • 8
  • 61
  • 86