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.
We'll cover the following...
We'll cover the following...
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
endUser defined diamond
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.
Know it first, then instruct computers
This an important aspect of programming. Once you figure out the pattern and logic ...