Just create a custom method:
def bool_to_int(bool)
bool ? 1 : 0
end
8*bool_to_int(v3) + 4*bool_to_int(v2) + 2*bool_to_int(v1) + bool_to_int(v0)
You can of course use an array and apply the function call to all the values in the list.
ary = [false, true, true, false]
exp = 0
ary.inject(0) do |total, value|
total += bool_to_int(value) * (2**exp)
exp += 1
total
end
This is more concise. The first item in the array is the exponent, the second is the sum.
ary = [false, true, true, false]
ary.inject([0,0]) do |(exp, total), value|
[exp + 1, total + bool_to_int(value) * (2**exp)]
end
As pointed out in the comments, you can also use <<
ary = [false, true, true, false]
ary.inject([0,0]) do |(exp, total), value|
[exp + 1, total + (bool_to_int(value) << exp)]
end