...

/

Solution: Printing a Diamond of Variable Size

Solution: Printing a Diamond of Variable Size

Go over the implementation of printing a variable-sized diamond shape.

Courtney's version

puts "Enter the maximum number of rows (odd number):"
size = gets.chomp.to_i
space = " "
space_count = size / 2 + 1
size.times do |row|
    if row < (size / 2 + 1)
        space_count -= 1
        hash_count  = row * 2 + 1
        print space * space_count
    else
        space_count += 1
        hash_count = (size - 1 - row) * 2 + 1 
        print space * space_count
    end
    puts '#' * hash_count 
end
User defined diamond

Explanation

  • Line 2: We get input from the user and convert the string input to integer type using .to_i at the end of the gets.chomp.

  • Line 5: We iterate through size.times, which is similar to 8.times seen previously, with the row variable serving as the looping index.

Courtney says

When I first tried replacing diamond size with user input variable, I forgot to change the variables and that made the outcome completely different. It wasn’t hard to fix it though.

This an important aspect of programming. Once you figure out the pattern and logic ...