User Guide #03 - Ruby - Simple examples

Ruby, ruby lesson, ruby уроки, user guide, руководство пользователя

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.
Support the author Donate

Comments

Only authorized users can post comments.
Please, Log in or Sign up
Donate

Hello, Dear Users of EVILEG!!!

If the site helped you, then support the development of the site financially, please.

You can do it by following ways:

Thank you, Evgenii Legotckoi

A
April 6, 2020, 5:24 a.m.
Alexey

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

  • Result:86points,
  • Rating points6
R
April 5, 2020, 2:32 p.m.
Roman

C++ - Test 002. Constants

  • Result:91points,
  • Rating points8
AP
April 5, 2020, 2:31 p.m.
Alexander Peshkov

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

  • Result:60points,
  • Rating points-1
Last comments
April 3, 2020, 8:06 a.m.
Konstantin Grudnitskiy

Я надеюсь вы уже разобрались в чем дело, но если вдруг нет, то проблема состоит в том, что вы пытаетесь запустить программу из интерпретатора питона. Файл main.py это уже готова…
April 3, 2020, 6:18 a.m.
Konstantin Grudnitskiy

>>> text = 'hello world'>>> ' '.join(word for word in text.split()[:-1])'hello'>>> def remove_last_word(text):... return text and ' '.join(word for word in text.s…
March 27, 2020, 2:40 p.m.
Evgenij Legotskoj

Добрый день. В конце пятой статьи скачать можете.
March 27, 2020, 2:28 p.m.
mkdir _

Здравствуйте, а можно, пожалуйста, ссылку на целые исходники, если есть?
March 27, 2020, 4:36 a.m.
Evgenij Legotskoj

Скорее всего также, как и для установки всех остальных переменых в CMake, через использование set
Now discuss on the forum
s
April 6, 2020, 8:06 a.m.
shuric

Добрый день. Объясните пожалуйста ... ... допиливать стилевое оформление в прокси классе ... где именно копать ? В каком виртуальном методе лучше допиливать (если можно н…
April 6, 2020, 4:19 a.m.
Evgenij Legotskoj

Попробуй не переустанавливать материал, а просто менять цвет
April 5, 2020, 11:38 a.m.
Mihailll

Так работает windeployqt --qmldir E:\QTProject\testQmlAndCpp E:\test\build-testQmlAndCpp-Desktop_Qt_5_14_1_MinGW_32_bit-Release
April 5, 2020, 2:35 a.m.
Mihailll

Так работает console.log(textEmail.text) var str = textEmail.text; var n = str.search(/^((([0-9A-Za-z]{1}[-0-9A-z\.]{1,}[0-9A-Za-z]{1})|([0-9А-Яа-я]{1}[-0-9А-я\.]{1,}[…
April 3, 2020, 8:48 a.m.
Intruder

Евгений, добрый день. Спасибо!
EVILEG
About
Services
© EVILEG 2015-2019
Recommend hosting TIMEWEB