Search⌘ K
AI Features

Solution: Printing a Diamond of Variable Size

Understand how to create a diamond shape in Ruby by taking user input to control size. Learn to implement loops and conditional logic, emphasizing problem-solving and translating patterns into scalable code.

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

Ask