Evgenii Legotckoi
Evgenii LegotckoiJune 18, 2016, 1:36 a.m.

User Guide #03 - Ruby - Simple examples

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

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

In ruby, this can be written as:

def fact(n)
  if n == 0
    1
  else
    n * fact(n-1)
  end
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:

# The program finds the factorial of the number
# Save this file as fact.rb

def fact(n)
  if n == 0
    1
  else
    n * fact(n-1)
  end
end

print fact(ARGV[0].to_i), "\n"

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

to_i
converts a character string to an integer.

% ruby fact.rb 1
1
% ruby fact.rb 5
120

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

% ruby fact.rb 40
815915283247897734345611269596115894272000000000

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

% ruby fact.rb 400
64034522846623895262347970319503005850702583026002959458684
44594280239716918683143627847864746326467629435057503585681
08482981628835174352289619886468029979373416541508381624264
61942352307046244325015114448670890662773914918117331955996
44070954967134529047702032243491121079759328079510154537266
72516278778900093497637657103263503315339653498683868313393
52024373788157786791506311858702618270169819740062983025308
59129834616227230455833952075961150530223608681043329725519
48526744322324386699484224042325998055516106359423769613992 
31917134063858996537970147827206606320217379472010321356624 
61380907794230459736069956759583609615871512991382228657857 
95493616176544804532220078258184008484364155912294542753848 
03558374518022675900061399560145595206127211192918105032491 
00800000000000000000000000000000000000000000000000000000000 
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:

% ruby
print "hello world\n"
print "good-bye world\n"
^D
hello world
good-bye world

Ruby also comes with a program called

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

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

% ruby eval.rb
ruby> print "Hello, world.\n"
Hello, world.
   nil
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.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
e
  • ehot
  • March 31, 2024, 9:29 p.m.

C++ - Тест 003. Условия и циклы

  • Result:78points,
  • Rating points2
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

C++ - Test 001. The first program and data types

  • Result:46points,
  • Rating points-6
Last comments
k
kmssrFeb. 9, 2024, 2:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 6:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 4:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 5:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
a
a_vlasovApril 14, 2024, 1:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 9:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 11:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…
AC
Alexandru CodreanuJan. 19, 2024, 7:57 p.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…

Follow us in social networks