Using the Ruby Interactive Shell
It is also called irb. It allows us to type ruby expressions or statements. Open the command prompt and type irb. (both Windows and Macintosh).
![Using Ruby Shell Command]()
As you can see in the above screen, we can write ruby expressions and statements. The texts entered within quotes are called String. We can perform Concatenation Operation (concatenation - Joining two Strings) on two strings.
We can store the value to the variable simply like,
name = “Welcome to Ruby!”
Ruby is a case sensitive programming language. So, name is different from Name and NAME.
We can also perform some complicated operations. See the below code snippet which prints numbers from 1 to 9.
i = 1
while i < 10
print i
end
![Wrong Example]()
Output :
![Wrong Output]()
Whoa!! What just happened? You might be confused after seeing the output. We said it prints 1 to 9. But it's showing all 1's and that also too many. This is because the variable i
was not incremented. Press Ctrl + C to terminate the execution.
The following code prints from 1 to 9
i = 1
while i < 10
print i
i += 1
end
We can also define functions in irb
. A function is a set of statement(s) to perform a particular task. Here is a function that returns square of a number.
def square(n)
return n * n
end
Calling the function: square (4)
Calling this function and passing 4 as argument returns 16 by performing the operation 4 * 4
. Likewise, a function to find the area of a circle.
def circle(radius)
return radius * radius * 3.14
end
Calling the function: circle (5)
and passing 5 as argument. This function returns 78.5 by multiplying 5 * 5 * 3.14
Ruby Scripts
We are going to run ruby from a text editor rather that a Command Prompt. You can use any text editor like Notepad, Notepad++, Sublime, Brackets. Ruby scripts have .rb extension. So, you have to save the file with the extension .rb
. Now, in your editor enter the following code and save it with any name with .rb
extension:
puts "Welcome to Ruby!"
Let's save this as first.rb. To run the program, go to Command Prompt, and type ruby first.rb
. You can also run by simply typing first.rb
as well, if during installation, "Add Ruby executables to your PATH" option was checked.
![Using Ruby Shell Command]()
Likewise, you can use any text editor in Macintosh and follow the same procedures as in Windows.