def sum_string_sizes(units)
units.inject(0) {|memo, unit| memo + unit.size }
end
units = %w{ one two three four five six seven eight nine }
sum_string_sizes(units)
=> 36
Refactorings
No refactoring yet !
macournoyer
September 19, 2007, September 19, 2007 19:52, permalink
You don't have to count the sizes separately, just join them up in one big string and you're almost done!
units = %w{ one two three four five six seven eight nine }
units.join.size # => 36
Hampton
September 21, 2007, September 21, 2007 09:11, permalink
Just another way to do it. Very similar.
units = %w{ one two three four five six seven eight nine }
units.sum { |i| i.size } #=> 36
# A shorter equivalent if ActiveSupport is around
units.sum &:size #=> 36
# Sum acts like join on an array of strings and is one character shorter if we are counting. ;)
units.sum.size
Hampton
September 21, 2007, September 21, 2007 09:20, permalink
I also want to write the most complex solution to this one. That is, the most complex solution that has no parts that aren't moving towards the solution.
For instance, to_s.to_i.to_s is not out of the rules.
DefactorMyCode.com
units = %w{ one two three four five six seven eight nine }
(units.collect do |item|
item.size
end).sum
# Or, even more
counts = (units.collect do |item|
counter = 0
item.to_a.each do |character|
counter = counter + 1
end
counter
end)
total_size = 0
counts.each do |size|
total_size = total_size + size
end
total_size
macournoyer
September 21, 2007, September 21, 2007 10:13, permalink
Welcome to the site Hampton! Nice defactoring!
But... counting in memory ?? This is so old school! Using file is much much faster, better, stronger!!
units = %w{ one two three four five six seven eight nine }
File.open('counter.txt', 'w') do |f|
units.each do |unit|
f << unit
end
end
puts File.size('counter.txt')
Vamsee
October 4, 2007, October 04, 2007 07:04, permalink
units = %w{ one two three four five six seven eight nine }
p units.join.length
Vamsee
October 4, 2007, October 04, 2007 07:05, permalink
Ahhh111, Sorry for dupe macournoyer alredy posted.
macournoyer
October 4, 2007, October 04, 2007 09:52, permalink
plus you used length +2 chars, ouch! :p
This code is functional, but ugly. Only after publishing it did I look at it critically. Show me your way.