I am trying to convert a bit array, such as [0,0,1,0].to_i = 2 or [0,1,0,1].to_i = 5.
What possible ways are there to do this in Ruby?
Here's a slightly more sophisticated snippet (as compared to Ryan's).
a1 = [0,0,1,0]
a2 = [0,1,0,1]
def convert a
a.reverse.each.with_index.reduce(0) do |memo, (val, idx)|
memo |= val << idx
end
end
convert a1 # => 2
convert a2 # => 5
.reverse instead of .reverse! make a difference? If I understood correctly, the first one should consume double the memory, rightreverse! mutates the original array. This has many consequences. One of which is if you convert the same array twice, you'll get different results. convert(a1); convert(a1)reverse.each, we can use reverse_each which does not build a temp array and does not touch the original array.
input.to_s(2).each_char.map { |c| c == '1' }isn't cutting it for huge numbers.