re: Daily Challenge #2 - String Diamond VIEW POST

FULL DISCUSSION
 

Ruby Language Version

def diamond carats
  return unless carats > 0 && carats.odd?
  top = 1.step(carats, 2).map{|i| (" " * ((carats - i) / 2)) << ("*" * i)}
  bottom = top.reverse[1..-1]
  (top + bottom).join("\n")
rescue
  nil
end

10.times{|i| puts diamond(i) }

require "spec"

describe "#diamond" do
  it { expect(diamond -1).to be_nil }
  it { expect(diamond 0).to be_nil }
  it { expect(diamond 3.0).to be_nil }
  it { expect(diamond 4).to be_nil }
  it { expect(diamond "foo").to be_nil }
  it { expect(diamond 1).to eq "*" }
  it { expect(diamond 3).to eq " *\n***\n *" }
  it { expect(diamond 5).to eq "  *\n ***\n*****\n ***\n  *" }
  it { expect(diamond 7).to eq "   *\n  ***\n *****\n*******\n *****\n  ***\n   *" }
  it { expect(diamond 9).to eq "    *\n   ***\n  *****\n *******\n*********\n *******\n  *****\n   ***\n    *" }
  it { expect(diamond 11).to eq "     *\n    ***\n   *****\n  *******\n *********\n***********\n *********\n  *******\n   *****\n    ***\n     *" }
end

output

>> rspec diamond.rb

*

 *
***
 *

  *
 ***
*****
 ***
  *

   *
  ***
 *****
*******
 *****
  ***
   *

    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *
...........

Finished in 0.00719 seconds (files took 0.15133 seconds to load)
11 examples, 0 failures
code of conduct - report abuse