Pregunta

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?

¿Fue útil?

Solución

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(:|)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top