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.
1 Answer 1
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") }
-
\$\begingroup\$ no need to
chomp
beforeto_i
."123\n".to_i => 123
\$\endgroup\$Selman Ulug– Selman Ulug2012年04月09日 07:16:38 +00:00Commented Apr 9, 2012 at 7:16 -
\$\begingroup\$ Why would you recommend IO.readlines and enum methods as opposed to a stream? \$\endgroup\$zzzzzzzzzzzzzzzzzzz77777777777– zzzzzzzzzzzzzzzzzzz777777777772012年04月09日 14:19:42 +00:00Commented Apr 9, 2012 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– Can Hanhan2012年04月09日 14:38:41 +00:00Commented Apr 9, 2012 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– Can Hanhan2012年04月09日 14:43:29 +00:00Commented Apr 9, 2012 at 14:43
-
\$\begingroup\$ Ok thanks! That helps a lot. Any other recommendations for screencasts on Ruby/RoR to watch? \$\endgroup\$zzzzzzzzzzzzzzzzzzz77777777777– zzzzzzzzzzzzzzzzzzz777777777772012年04月11日 01:12:31 +00:00Commented Apr 11, 2012 at 1:12