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
>> rspec diamond.rb * * *** * * *** ***** *** * * *** ***** ******* ***** *** * * *** ***** ******* ********* ******* ***** *** * ........... Finished in 0.00719 seconds (files took 0.15133 seconds to load) 11 examples, 0 failures
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Ruby Language Version
output