Learn to program with Ruby #Issue2

in #utopian-io6 years ago (edited)

ruby.jpg
Image Source

What Will I Learn?


Learning to program can be done with any general language: the same rules basic are used regardless of the language. However, some are closer than others to the human logic and therefore better adapted to the learning of programming. This is the case of Ruby.

  • You will learn Predefined methods of Ruby
  • You will learn Variables and constants
  • You will learn The gets method

Requirements


Difficulty


  • Intermediate

Tutorial Contents


Predefined methods

For each class, there are dozens of predefined methods. We can display the list of methods applicable to a class by typing the following:
NameClasse.instance_methods
For example, if we type String.instance_methods in irb (the name of the class must start by a capital letter), we obtain this:
rbt7.png

Some methods end with a question mark. These are Boolean methods, tests that can only return true (true) or false (false).
For example, if we type to a class by typing the following: if we type"test" .empty? (including the question mark final), which means the "string of characters" test "is it of length nothing ? The answer will be false. Conversely, if you type "" .empty?, the answer will be true since there is no character between the two quotation marks.

For Ruby, a chain of characters is a list of items. This allows, for example, to look for the position of a
character. The method is index ("c"). The first character occupies position 0, the second the position 1, etc. The language differentiates lowercase and uppercase.

So, in the example opposite, he sees the capital letter S at position 0 and the lowercase letter s at position 3. It is important to note that space is a character too.

The numerical operations are the usual operations: the addition (+), the subtraction (-), the multiplication (), division (/), power (*), etc. For example, the expression x ** 3 means x3.
If you put a number in quotation marks or quotation marks, it's a string of characters. By example, "4" + "3" gives "43". This operation is a concatenation. We can also multiply characters. By example, "4" * 3 gives "444" while 4 * 3 gives 12.
rbt8.png

The Math.sqrt (x) method gives the square root of x.
The result of sqrt is automatically a real number. To enclose a chain of characters, quotation marks are not the only solution. We can also use the apostrophes, but in this case, Ruby restores the character string as it receives it. With the quotation marks, he look for possible variables, which must be preceded by a pound sign and between braces, or characters control.

The most common command character is "\ n", which commands a line break (as in many other languages). There are ten others, including "\ t" for tab and "\ s" for a space, but they are less useful.


Variables and constants

In all computer languages, if we want to preserve values, we place them in variables.

A normal variable is a local variable, which means that it exists only in the block of code where it is created. In Ruby, a local variable must start a lowercase letter or a underscore character (this is how he recognizes it as local). It can consist of unaccented characters, numbers, and the underscore character.
For example, result, sum1, _ plus, totalBrut and total_net are variables, but not 1st or Name because a variable must not start with a number or a capital letter.
This rule is also valid for method names and names method parameters.
We perform on the variables the same operations as with numbers. A global variable exists in the entire program. His name starts with the sign $.

A variable whose value must not change is a constant. She begins with a capital letter. An example is the number pi, which we can write PI or Pi.If you change the value of a constant, Ruby obeys but displays a warning message.


Tables and hashes

In Ruby, a table is a set of indexed items. The term "indexed" simply means that each element is numbered and that one can search for an element by giving number, which is called his key.
When creating a table, we separate the elements by brackets:
tableName = ["element1", "element2", etc. ]

They number themselves automatically from scratch. The first element receives the number 0, the
second 1, etc. There is another type of collection, the associative array or hash, which differs from the table normal in that the key does not have to be an integer. Anything is ok.

When we create a hash, we separate the elements by braces. The keys must be indicated:
nameHash = {"key1" => "element1", "key2" => "element2", etc. }
On the other hand, when using, we use braces, but hooks as with a table.


Create a method

To create a method, we use the def ... end construct.
We can specify arguments, or parameters, that is to say elements on which the action must be done.
If there are any arguments, put them in parentheses after the name of the method, in the form def method-name (parameter1, parameter2, etc.). Here is an example -

def poster (message)
 puts message
end

So, once the radius_to_area and round_to methods are created, type the following:
puts radius_to_area (3) .round_to (2) Ruby answers 28.27 instead of 28.27433388231.


The gets method

A very useful method is gets (get string). It allows the program to read what the user type on the keyboard.
The classic syntax is:
answer = gets.chomp
The gets method places in the response variable the characters entered by the user, including the Enter with which he finished typing. The chomp method has the effect of removing characters endnotes "\ n" which represent this Enter. For example, if the user typed "o" for "yes", gets records "o \ n". It is necessary to use gets.chomp so that the method gets rid of the Enter and keeps only the letter "o".
If the program is waiting for a character response, usually adds the downcase or upcase method:
answer = gets.chomp.downcase

Without this, when the user types "o" or "n", it would be necessary to treat twice his answer: "if the answer is" o "lowercase or" O "uppercase, so... ". With the downcase, we can be satisfied with "if the answer is "o" tiny, so ... ".
If we want the user's input to be a number instead of a string, we need use gets.to_f or gets.to_i depending on the type of number you want:
answer_numerical = gets.to_i
In this case, the chomp is useless because the to_i and to_f methods get rid of any way of the final signs "\ n" since they are not numbers.
Without this, when the user types "o" or "n", it would be necessary to treat twice his answer: "if the answer is" o "lowercase or" O "uppercase, so... ". With the downcase, we can be satisfied with "if the answer is "o" tiny, so ... ".
If we want the user's input to be a number instead of a string, we need use gets.to_f or gets.to_i depending on the type of number you want:
answer_numerical = gets.to_i
In this case, the chomp is useless because the to_i and to_f methods get rid of any way of the final signs "\ n" since they are not numbers.


The Conditions

In the course of a program, connections are often needed. This is the case,
example, whether or not to start a treatment according to the user's request: "if the answer is yes, do this ... if not do that ... ". All computer languages ​​can be used to manage connections.
In Ruby, there are three branch constructions:
• case ... when ... when ... else ... end ("in case 1 ... in case 2 ... etc.")
• if ... elsif ... elsif ... else ... end ("if ... otherwise ...")
• unless ... elsif ... elsif ... else ... end ("unless ... otherwise ..." is the inverted

Here is an example with the if ... end construct:

 answer = gets.chomp.downcase
if answer == "o"
 puts "the answer is yes"
elsif answer == "n"
 puts "the answer is no"
else
 puts "answer not included"
end

Note that equality is written with an equal double sign ("=="). This sign is used to say an object is identical to another object whereas the simple equals sign ("=") is used to give a value to an object.
Here is an example with the unless ... construct:

puts "would you like to continue? (o / n)"
answer = gets.chomp.downcase
unless answer == "o"
 puts "then you want to stop"
end

The expression unless answer == "o" means "unless the answer is yes", which means, say
by the way, that all the answers except the lowercase or uppercase "o" are considered
like "no".
With both constructs, the elsif and the else are optional. There are four possible forms:
• if ... end (or unless ... end)
• if ... else ... end
• if ... elsif ... end
• if ... elsif ... else ... end

Curriculum


Learn to program with Ruby #Issue1

Thanks For Reading



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Thanks For The Approval. I'm glad to make this contribution.