Avatar

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?

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 !

37cebc7c6f4cee5d5bc34277e691e7ba

Matt Downey

June 19, 2010, June 19, 2010 01:46, permalink

1 rating. Login to rate!

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."
Avatar

thaostra.myopenid.com

June 19, 2010, June 19, 2010 04:37, permalink

1 rating. Login to rate!

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

Your refactoring





Format Copy from initial code

or Cancel