Evgenii Legotckoi
June 18, 2016, 11:36 a.m.

User Guide #03 - Ruby - Simple examples

Let's write a function to compute factorials. The mathematical definition of n factorial is:

  1. n! = 1 (when n==0)
  2. = n * (n-1)! (otherwise)

In ruby, this can be written as:

  1. def fact(n)
  2. if n == 0
  3. 1
  4. else
  5. n * fact(n-1)
  6. end
  7. end

You may notice the repeated occurrence of end . Ruby has been called "Algol-like" because of this. (Actually, the syntax of ruby more closely mimics that of a langage named Eiffel.) You may also notice the lack of a return statement. It is unneeded because a ruby function returns the last thing that was evaluated in it. Use of a return statement here is permissible but unnecessary.


Let's try out our factorial function. Adding one line of code gives us a working program:

  1. # The program finds the factorial of the number
  2. # Save this file as fact.rb
  3.  
  4. def fact(n)
  5. if n == 0
  6. 1
  7. else
  8. n * fact(n-1)
  9. end
  10. end
  11.  
  12. print fact(ARGV[0].to_i), "\n"

Here, ARGV is an array which contains the command line arguments, and

  1. to_i
converts a character string to an integer.

  1. % ruby fact.rb 1
  2. 1
  3. % ruby fact.rb 5
  4. 120

Does it work with an argument of 40? It would make your calculator overflow...

  1. % ruby fact.rb 40
  2. 815915283247897734345611269596115894272000000000

It does work. Indeed, ruby can deal with any integer which is allowed by your machine's memory. So 400! can be calculated:

  1. % ruby fact.rb 400
  2. 64034522846623895262347970319503005850702583026002959458684
  3. 44594280239716918683143627847864746326467629435057503585681
  4. 08482981628835174352289619886468029979373416541508381624264
  5. 61942352307046244325015114448670890662773914918117331955996
  6. 44070954967134529047702032243491121079759328079510154537266
  7. 72516278778900093497637657103263503315339653498683868313393
  8. 52024373788157786791506311858702618270169819740062983025308
  9. 59129834616227230455833952075961150530223608681043329725519
  10. 48526744322324386699484224042325998055516106359423769613992
  11. 31917134063858996537970147827206606320217379472010321356624
  12. 61380907794230459736069956759583609615871512991382228657857
  13. 95493616176544804532220078258184008484364155912294542753848
  14. 03558374518022675900061399560145595206127211192918105032491
  15. 00800000000000000000000000000000000000000000000000000000000
  16. 0000000000000000000000000000000000000000000

We cannot check the correctness at a glance, but it must be right.

The input/evaluation loop

When you invoke ruby with no arguments, it reads commands from standard input and executes them after the end of input:

  1. % ruby
  2. print "hello world\n"
  3. print "good-bye world\n"
  4. ^D
  5. hello world
  6. good-bye world

Ruby also comes with a program called

  1. eval.rb
that allows you to enter ruby code from the keyboard in an interactive loop, showing you the results as you go. It will be used extensively through the rest of the tutorial.

If you have an ANSI-compliant terminal (this is almost certainly true if you are running some flavor of UNIX; under DOS you need to have installed ANSI.SYS or ANSI.CON ), you should use this eval.rb , that adds visual indenting assistance, warning reports, and color highlighting. Otherwise, look in the

  1. sample
subdirectory of the ruby distribution for the non-ANSI version that works on any terminal. Here is a short eval.rb session:

  1. % ruby eval.rb
  2. ruby> print "Hello, world.\n"
  3. Hello, world.
  4. nil
  5. ruby> exit

hello world is produced by print . The next line, in this case nil , reports on whatever was last evaluated; ruby does not distinguish between statements and expressions , so evaluating a piece of code basically means the same thing as executing it. Here, nil indicates that print does not return a meaningful value. Note that we can leave this interpreter loop by saying exit, although Ctrl + D still works too.

Throughout this guide, "ruby>" denotes the input prompt for our useful little eval.rb program.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup