4
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

I would not open a stream instead use IO.readlines and enum methods:

puts File.readlines("decimals.txt").reduce(0) { |total, line| total += line.chomp.to_i.to_s(2).count("1") }
\$\endgroup\$
  • \$\begingroup\$ no need to chomp before to_i. "123\n".to_i => 123 \$\endgroup\$ – Selman Ulug Apr 9 '12 at 7:16
  • \$\begingroup\$ Why would you recommend IO.readlines and enum methods as opposed to a stream? \$\endgroup\$ – zzzzzzzzzzzzzzzzzzz77777777777 Apr 9 '12 at 14:19
  • \$\begingroup\$ 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 \$\endgroup\$ – Can Hanhan Apr 9 '12 at 14:38
  • \$\begingroup\$ By the way, you should watch The Enumerable Module or How I fell in Love with Ruby if you have not yet \$\endgroup\$ – Can Hanhan Apr 9 '12 at 14:43
  • \$\begingroup\$ Ok thanks! That helps a lot. Any other recommendations for screencasts on Ruby/RoR to watch? \$\endgroup\$ – zzzzzzzzzzzzzzzzzzz77777777777 Apr 11 '12 at 1:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.