First steps in ruby. Printing a triangle of stars

I’m going to try and write some simple ruby programs. Here’s the first one. It prints a triangle of stars like this:

1
2
3
4
5
6
7
8
9
10
11
*
**
***
****
*****
******
*******
********
*********
**********
***********

And here is the code:

1
2
3
4
5
6
star_string = "*"
 
10.times do
    puts star_string
    star_string = star_string + "*"
end

I hope you can understand it. The program creates a string called “star_string”. Then it loops 10 times. Each time it loops it prints (puts) out star_string, and adds another * to the string. That way star_string gets longer and longer.

I’m also going to show you how this is done in C++. If you don’t want to learn C++ you don’t need to look at this. But C like languages are so common it’s worth at least gaining some familiarity with the syntax.

#include
#include

using namespace std;

int main() {

string star_string = “*”;

for(int n=0;n<10;n++) { cout << star_string << endl; star_string = star_string + "*"; } } [/sourcecode] Can you modify the program so it prints more than one triangle, like this? [sourcecode language="html"] * ** *** **** ***** ****** ******* ******** ********* ********** * ** *** **** ***** ****** ******* ******** ********* ********** [/sourcecode] Post your solution in the comments sections below. Everytime someone posts a solution, I'll try to post a new example and problem the next day. The part 2 is now HERE.

7 Comments

  1. new299 says:

    btw, there are some notes on using Ruby on Mac OS X and other platforms here.

  2. gaffer says:

    Or for a more rubyish way:


    10.times do |n|
    puts "*" * n
    end

  3. new299 says:

    I’m not sure what “rubyish” means in this case. I’ve just started learning Ruby. Is “* n” a universal concept in Ruby? (i.e. repeat the previous statement n times) or does it only apply to puts? I take it |n| means put the current number of iterations in n?

  4. Neko says:

    Thank you for your post! I tried it.

    2.times do
    star_string = “*”
    10.times do
    puts star_string
    star_string = star_string + “*”
    end
    end

    P.S. It’s not a star☆ 🙂

  5. […] First steps in ruby 2: Variables and chop 01. October 2011 · Write a comment · Categories: Uncategorized This builds on the pervious article here. […]

  6. radley says:

    here is an empty triangle code

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

    while (count 2 && count < user_num)
    if(count == user_num)
    break
    end
    puts"*" + " " * (count – 2) + "*"
    count+=1
    end
    end

  7. Said GUERRAB says:

    Here’s a simple way to print a perfect pyramid with ruby:
    while i <=50
    if i.odd?
    puts(print ("*"*i).center(100))
    end
    i +=1
    end

Leave a Reply