# Binary numbers challenge

I don't know if this is exactly refactoring but I recently completed a programming challenge to learn more about Ruby's iterators. However, I feel that the code is extremely "un-Ruby like". Would anyone have any suggestions as to how I could improve it?

numbers = []
binary = []
binary_count = 0

File.open('decimals.txt').each_line do |line|
numbers.push line.chomp
end

numbers.each do |number|
binary.push number.to_i.to_s(2)
end

binary.each do |binary_num|
binary_count += binary_num.count("1")
end

puts binary_count


Yes, I know it's a basic problem. It took me roughly five minutes to complete but it was more about just getting the syntax of the iterators down.

puts File.readlines("decimals.txt").reduce(0) { |total, line| total += line.chomp.to_i.to_s(2).count("1") }

• no need to chomp before to_i. "123\n".to_i => 123 Apr 9, 2012 at 7:16
• IO.readlines returns array of lines as your first block does. it also ensures the stream is closed and its native implementation is more optimized than the Ruby code. It is very easy to read in the code and explains the intention better. Enumerable methods are the coolest part of Ruby. Beside coolness, there is no point to keep 2 arrays + 1 stream in the memory for no reason. You have 3 star actors in the cast who never show up in the movie. It is much easier to understand shorter, but not too short, code. Only thing that I do not like is to_i.to_s(2) which would be better: to_binary Apr 9, 2012 at 14:38