Try this:
x = 5.to_s(2).split(//).collect do |n|
n == "1"
end
p x
Question
Okay, so I was wondering if I could create an array of Boolean values from an integer by using its bits. For example, if I wanted to use 5, which is 101 in binary, is there any reasonably easy way that I could get this in something of the form:
[true, false, true]
The idea is that a one would be a true and zero would be a false. It would be adequate to get it as an array of zeros and ones but true and false would be much more preferable.
Thanks in advance for any help.
Solution
Try this:
x = 5.to_s(2).split(//).collect do |n|
n == "1"
end
p x
OTHER TIPS
This would work:
num = 5
(0...num.bit_length).map { |i| num[i] == 1 }
#=> [true, false, true]
or
(0...num.bit_length).map { |i| num[i] == 1 }.reverse
#=> [true, false, true]
depending on the desired bit order.
See this answer of mine to a similar question: Looping through bits in an integer.
Here's the gist of it:
In Ruby,
Integer
s (i.e. bothBignum
s andFixnum
s) can already be indexed as if they were bit arrays. They are, however, notEnumerable
.But you can fix that, of course:
class Integer include Enumerable def each return to_enum unless block_given? (size*8).times {|i| yield self[i] } end end
A slightly less intrusive way might be to represent the
Integer
as an array:class Integer def to_a Array.new(size*8, &method(:[])) end end
Then you can use Ruby's nifty
Enumerable
methods:
5.to_a.map {|b| !b.zero? }
# => [true, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]