In learning Ruby I've dug out some old C++ exercises and one in particular which can be found here deals with a for loop. I'm basically converting the C++ code to Ruby code. I won't repeat the C++ code but the exercise is as follows:

Write a C++ program that asks the user to enter a number of rows to be printed. It should then display for the first row one asterisk preceded by periods. The second row should display two asterisks preceded by periods and so on until all the rows have been printed as entered by the user.

A sample run would be like so:

Enter number of rows: 5
....*
...**
..***
.****
*****

It seemed to take me ages to get my head around the structure of for loops and I ended up firstly using while loops just to get the program working. After that I eventually got this for loop version working.

# nestedforloop.rb
# 19 Apr, 2009.
print "Enter the number of rows: "
rows = gets.chomp!
rows = rows.to_i

for r in (1..rows)
  for c in (1..(rows - r))
    print "."
  end
  r == rows ? c = 1 : c += 1
  for c in (c..rows)
    print "*"
  end
  print "\n"
end

The above works but I'm thinking maybe there was a way I didn't need to use the r == rows ? c = 1 : c += 1 line, as that wasn't necessary under the C++ for loop/code. Should I stop thinking in terms of how traditional for loops are structured? I'm led to believe that for is in fact an alias (if that's the right word) of the each method. Any hints re - using the each method would be appreciated (as applied to the above).

Here are some suggestions I've since received from other sources. In essence there is always more than one way to skin a cat.

for r in (1..rows)
  for c in (1..(rows - r))
    print "."
  end
  for c in ((rows - r)...rows) # improvement here, notice 3 dots
    print "*"
  end
  print "\n"
end

Here's another solution and not as many lines of code required.

print "Enter the number of rows: "
rows = gets.strip.to_i

rows.times do |row|
  print '.' * (rows-row-1)
  print '*' * (row+1)
  puts ''
end
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.