Search code examples
rubydictionarymethodsdrawingnewline

How do I make a Ruby method that makes a diamond of asterisks with 'n' width?


I'm trying to make a method that returns a string that looks like a diamond shape when printed on the screen, using asterisk (*) characters. I want to remove any trailing characters and each line to be terminated with a (\n). I also want it to return nil if the input is an even number or negative, as it is not possible to print a diamond of even or negative size. For example

       *
n=3   ***
       * 

        *
       ***
n=5   *****
       ***
        *

or in other words

"  *\n ***\n*****\n ***\n  *\n"

Method looking something like this:

def diamond(n)
  
end

Can anyone help? Thanks!


Solution

  • Another solution:

    def diamond(n)
      return nil if n.even? || n.negative?
      
      diamond_string = ""
      n.times do |i|
        space_count = (i - n / 2).abs
        asterisk_count = n - space_count * 2
        diamond_string << [' ' * space_count, '*' * asterisk_count].join + "\n"
      end
    
      return diamond_string
    end