Ruby

Ruby

Ruby is a scripting language that is becoming more popular.  You will notice that Ruby has a lot of similarities with Python, so your knowledge of Python will be extremely beneficial!


During this section we will cover:


To continue to improve on your Ruby skills learnrubyonline.org is a great site. You can also test Ruby code at: https://runrb.io/.


As the Python Page provide details about what each element is we will just look at examples on how to use Ruby.

Variables

Variables in Ruby do differ a little bit from python. There are five types of variables. Do not worry about how to use 2 - 5 in the list below, but just now they exist. We will just focus on local variables at this moment.


The five type of variables are:


Local variable example:


luckynumber = 30

multiplier = 100

total = luckynumber * multiplier

puts total


This creates three variables, luckynumber with a value of 30, multiplier with a value of 100 and total with a value of 3000 (30 * 100). The last line with puts writes the output standard out.

Arrays

Creating and using arrays differs in Ruby.  In Ruby we need to create a variable that will be our array and initialize this as a new array using the Array class. 


arr = Array.new()

arr2 = Array.new(20)

arr3 = ["A", "B", "C", "D"]

The first line of code creates a new array, but does not define the size. The second line of code passes 20 as a parameter to the new method that defines the size of the array. The third line creates an array and assigns elements to the array. 


To access an element within the array is just like Python. 


arr3 = ["A", "B", "C", "D"]

puts arr[1]

The above code would output B.

Ruby Comparison Operators

The Ruby comparison operators are the same as Python.


Keep in mind that these can be used to compare numbers, strings and other data types.

String Operators

Just like Python you can define a string as a variable without needed to specify a data type. To learn more about the Ruby String class view the Ruby Documentation


first = "Pete"

last = "Gross"


full = first + " " + last

puts full  # Output: Pete Gross


Conditionals

Conditionals in Ruby have a small difference in syntax than Python. This is a great way to be able to quickly determine if the script is Ruby or Python. We will use the same example from Python, but update it to Ruby.


# Example of a Ruby conditional statement

x = 10


if x > 5

    puts "x is greater than 5"

else

    puts "x is less than or equal to 5"

end

Can you spot the difference in syntax? The first one is that we do not need to use the : character at the end of the if or else line. Also, Ruby clearly states the conditional has ended with the end keyword. 

Ruby also has a minor sytanx difference with an if-elsif-else statement. Ruby uses elsif while Python uses elif. 

# Example of a Ruby conditional statement with if-elsif-else.


x = 10


if x > 10

    puts "x is greater than 10"

elsif x < 10

    puts "x is less than 10"

else:

    puts "x is equal to 10"

Basic Looping

Ruby for and while loops are exactly like Python, except for minor sytanx differences. Hopefully, you are realizing that once you understand how to use one scripting language it is easy to pick up another one.


Ruby for loop example:

for a in 1..5 do

 puts a

end

This for loop iterates over the range 1 to 5 (including 5) and just counts up from 1 to 5.


Ruby while loop example:

x = 5

while x >= 0

  puts x

  x=x-1

end

This while loop counts down from 5 to 0.

Error Handling

Error handling in Ruby differs greatly from Python and what you have learned in ICS 111. It is not simple, but we will still look at the syntax with a brief explanation.


begin

    #Where an exception might occur

rescue =>

    #This handles the exception/error

else

    #This runs when there is no error

ensure

    #This is always run

end


Let us see an example using divide by zero error again.


begin

   numerator = 281

   denominator = 0

   puts numerator/denominator

rescue ZeroDivisionError => e

   puts "You can't divide by zero, change your denominator"

   puts e

end



System Calls

Ruby also provides the ability to make system calls. The first way is to use the system method. If the command was succesfully completed it will return true.  Using the system method the output will be displayed to the console.  The second way is to use backticks (` `) or %x{} syntax. This way of doing it allows the user to capture the output of the command and store it in a string value. The third way is to use exec() method. This does not provide a return value unless there is an error. The exec() method also replaces the current process with a new process. This means that anything after the exec() statement will not be run.


Example 1:

system("ls -l")

Example 2:

result = `ls -l`

Example 3:

result = %x(ls -l)

puts result

Example 4:

exec("ls -l")

puts "This will not be shown"