1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#!/usr/bin/env ruby 1.upto(10){ |i|puts "#{i} squared = #{i**2}" } puts 'Program Completed' =begin Outputs: 1 squared = 1 2 squared = 4 3 squared = 9 4 squared = 16 5 squared = 25 6 squared = 36 7 squared = 49 8 squared = 64 9 squared = 81 10 squared = 100 Program Completed =end
Refactorings
No refactoring yet !
Matt Downey
June 19, 2010, June 19, 2010 01:46, permalink
Looks crummy w/o whitespace, but this was as short as I could get it :)
1
puts (1..10).map{|i|"#{i} squared = #{i**2}"}<<"Program Complete."
thaostra.myopenid.com
June 19, 2010, June 19, 2010 04:37, permalink
I never thought about using the map method. Thanks. =D
My re-factored code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#!/usr/bin/env ruby puts (1..10).map{ |i|"#{i} squared = #{i**2}" }, 'Program Completed.' =begin Outputs: 1 squared = 1 2 squared = 4 3 squared = 9 4 squared = 16 5 squared = 25 6 squared = 36 7 squared = 49 8 squared = 64 9 squared = 81 10 squared = 100 Program Completed =end
I looked at the code examples at http://en.wikipedia.org/wiki/Spaghetti_code, and thought I could write a program which produces the same results in Ruby. However, being new to the language I am not sure if this program can be made more compact and concise. What do you guys think?