School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become an Expert!

Join 309,233 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 2,747 people online right now. Registration is fast and FREE... Join Now!




Making shapes with ruby.

 

Making shapes with ruby.

rogersj7

25 Oct, 2008 - 04:43 PM
Post #1

New D.I.C Head
*

Joined: 24 Oct, 2008
Posts: 3

hi,

I'm new to the ruby universe. I like figuring out problems with ruby to get used to it but I'm having a problem finding code to make shapes such as diamonds, circles and such.

Any idea where I can find them? I know I will use loops (def and such) but any help is welcome.

J.

User is offlineProfile CardPM
+Quote Post


Martyr2

RE: Making Shapes With Ruby.

25 Oct, 2008 - 07:05 PM
Post #2

Programming Theoretician
Group Icon

Joined: 18 Apr, 2007
Posts: 7,335



Thanked: 845 times
Expert In: C/C++, Java, VB, VB.NET, C#, PHP, Web Development, HTML & CSS, Javascript

My Contributions
Well in ruby shape making is pretty easy compared to some of the other languages that require a lot more syntax. Here is a rough example of building an X width diamond...

ruby

# Prompt for the number of columns in the middle of a diamond
puts "Enter the number of columns for the diamond: "
count = gets.chomp.to_i

# Loop from 1 up to the count they entered
# In each loop we loop from that many spaces for the row, then that many asterisks
# End with a new line. This forms the top of the diamond.
1.upto(count) do |i|
i.upto(count - 1) { print " " }
i.times { print " *" }
print "\n"
end

# Subtract 1 so we don't double up the middle row
count = count - 1

# Now go from count down to 1
count.downto(1) do |i|
i.upto(count) { print " " }
i.times { print " *" }
print "\n"
end


Essentially we ask for a number, loop from 1 to that number and construct the proper number of spaces and asterisks for each level until we get to the middle. Then we do the reverse to form the bottom half of the diamond.

As with all ruby this can be crunched down even further, but I wanted to keep this open enough so it wasn't too cryptic.

Hope it helps!

"At DIC we be diamond building with ruby code ninjas... we are the jewelers of the coding world." decap.gif
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic

Time is now: 11/26/09 08:52AM

Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month