A
A
arruah2019-01-25 20:29:30
ruby
arruah, 2019-01-25 20:29:30

How to build a rhombus using spaces and asterisks in ruby?

I am learning to program in Ruby. In the course, there is a task to build a rhombus in the console using spaces and asterisks. Decided to use .each to build nested loops.
I can't figure out how to build an algorithm for the bottom of the rhombus. The upper part also does not shine with elegance, but still the upper part of the rhombus is being built.
I found on the net how to build a rhombus in JS but could not figure out how to apply it in ruby.
My code:

puts "Enter height of the piramid: "
height = gets.chomp
height_result = height.to_i * 2
(1..height_result).each do |string_number|
  (1..height_result).each do |second_number|
    if string_number <= height.to_i
    space_count = height_result / 2 - string_number
    asterisk_count = height_result / 2 + string_number - 1 - space_count
    else
    space_count = string_number - height.to_i
    asterisk_count = height.to_i - space_count
   end
    print " " * space_count + "*" * asterisk_count
    break
   end
  print "\n"
end

The output is:
Enter height of the pyramid:
6
*
    ***
   *****
  *******
 *********
***********
 *****
  ****
   ***
    **
     *

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-01-25
@arruah

(1..height_result - 1).each do |n|
  space_count = (height.to_i - n).abs
  asterisk_count = height_result - space_count * 2 - 1
  print " " * space_count + "*" * asterisk_count + "\n"
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question