Today, in this write-up, let us see some basic concepts of Ruby language. This tutorial will help you learn the language easily.
What is Ruby?
It is a dynamic, object-oriented, general-purpose programming language. Now, let’s create our first program - the classic “Hello World” program.
For this, we will use the built-in “puts” method.
Another method that can be used to display the output on the screen is “print”.
The following code displays the same output as earlier except that the “puts” automatically adds a new line after the output, while “print” does not.
Comments
Comments are lines of annotation within Ruby code that are ignored at the program runtime. It uses a symbol of hashtag (#) for single-line comment.
For multiple-lines of comments, we use the “=begin” and “=end” keywords.
Variable
To insert the value of a variable into a double quote string, we use the “#” symbol and curly brackets with the variables name. Here, age is variable and 42 is the value of the variable.
Constants
Variables beginning with a capital letter and whose value, once assigned, can’t be changed are known as constants.
In the above example, the value has already been assigned for the constant variable. If we try to change the value of the variable, it will throw a warning or an error to the user.
Exponent Operator
The “**” symbol represents the exponent operator for raising a number to a power to perform exponentiation.
The output comes like this, 2*2*2*2*2 = 32.
Shorthand Assignment Operator
All of the arithmetic operators have corresponding shorthand forms for assignment. For example, “a = a + 8” can be written as “a + = 8”. The same applies to the other operators.
(e.g.),
x + = y # x = x + y
x - = y # x = x - y
x * = y # x = x * y
x / = y # x = x / y
x % = y # x = x % y
x ** = y # x = x ** y
String
String is a text between single or double quotes. However, some characters can’t be directly included in a string. Using the symbol “\” the string can be included.
Concatenation
Two strings can be joined using the “+” symbol. It doesn’t matter whether the strings are in single or double quotes.
Repeating a string
A string can be repeated using the “*” symbol and an integer value.
Here, the first “puts” method prints the three times “abc” and the second “puts” method prints 5 four times.
Getting user input
To get the input from the user, we use the “gets” method.
The above example program can be understood like this. After writing the code and selecting the Run command, it asks for some input from the user. After submitting the input value, it displays the output.
The “gets” method gets a line of text, including a new line at the end. If you don’t want to include the new line, use the “gets.chomp” method.
Today, we learned some basic concepts of Ruby. In my upcoming articles, we will see all the important concepts of this interesting language.