Bit counting / hamming weight / population count coding Kata (RUBY w/o to_s)

This coding kata was to write a method that takes an integer as input and ouputs the number of 1’s in the binary representation of that number.. i.e.:

The binary representation of 1234 is 10011010010, so the function should return 5 in this case

Here are my results:

def count_bits(n)
bin_values = [[1,0]]
while n > bin_values[0][0]
bin_values.insert(0, [(bin_values[0][0] * 2),(bin_values[0][1] + 1)])
n_bin = []
for i in 0..(bin_values.size - 1)
n_bin << '0'
p n
for val in bin_values
if n >= val[0]
n_bin[val[1]] = '1'
n = n - val[0]
n_bin[val[1]] = '0'
num_ones = 0
for num in n_bin
num == '1' ? num_ones += 1 : num_ones
return num_ones

The top line of code basically populates a lookup table where I populate based on the input integer.

The lookup table is an array where each element describes a binary position [Index value, Index]

The remaining code is relatively straight forward as a new array is populated based on how large the binary# will be (the size of the first array), then the lookup table is used to set the Index of the new array to a ‘1’ if the Index Value is less than n and subtracts the Index Value from n (this is done from largest to smallest).

Finally, all of the 1’s from the new array are added together for the final return value.