Skip to content

Instantly share code, notes, and snippets.

@barnes7td
Last active December 15, 2015 17:09
Show Gist options
  • Save barnes7td/5293864 to your computer and use it in GitHub Desktop.
Save barnes7td/5293864 to your computer and use it in GitHub Desktop.
Ruby challenge - diamond method
## Method 1 (used 2 methods)
def diamond(max_width)
string = ""
if max_width < 3
puts "*" if max_width == 1
puts "**" if max_width == 2
return nil
end
if max_width.even?
width = 2
else
width = 1
end
string << create_row(width, max_width)
while width < max_width
width += 2
string << "\n"
string << create_row(width, max_width)
end
while width > 2
width -= 2
string << "\n"
string << create_row(width, max_width)
end
puts string
end
def create_row(width, max_width)
spaces = (max_width - width) / 2
(" " * spaces) + ("*" * width)
end
#######################################################################
## Method 2
def diamond(max_width)
if max_width.even?
array = (2..max_width).to_a.select{|n| n.even?}
else
array = (1..max_width).to_a.select{|n| n.odd?}
end
array = array + array.reverse[1..-1]
string = ""
array.each_with_index do |width, index|
spaces = (max_width - width) / 2
string << (" " * spaces) + ("*" * width)
string << "\n" unless index == array.length - 1
end
puts string
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment