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.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Apr 9, 2012 at 5:03
\$\endgroup\$

1 Answer 1

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") }
answered Apr 9, 2012 at 6:17
\$\endgroup\$
5
  • \$\begingroup\$ no need to chomp before to_i. "123\n".to_i => 123 \$\endgroup\$ Commented Apr 9, 2012 at 7:16
  • \$\begingroup\$ Why would you recommend IO.readlines and enum methods as opposed to a stream? \$\endgroup\$ Commented 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\$ Commented 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\$ Commented Apr 9, 2012 at 14:43
  • \$\begingroup\$ Ok thanks! That helps a lot. Any other recommendations for screencasts on Ruby/RoR to watch? \$\endgroup\$ Commented Apr 11, 2012 at 1:12

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.