Introduction to Ruby

Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features (thanks Wikipedia). Its creator is Yukihiro Matsumoto aka “Matz”. Simply put, Ruby is a really powerful, genuinely object-oriented scripting language and the best part about it is: its quite easy to learn.

Installation

To install Ruby, visit the downloads page at Ruby-Lang.org. You can check if the installation went correctly by running ruby -v from the shell prompt.

If the installation was successful, fire up Interactive Ruby (IRB) by typing irb from the run menu. You can also open irb.bat from the installation folder. You do not need a fancy editor for this tutorial. The Interactive Ruby (IRB) console would suffice.

Getting and Showing Input

Let’s start off with an easy program.

puts("Hello World")
print("Hello World")

Can you tell the difference between puts and print by looking at the snapshot above? Answer: puts adds a linefeed but print does not.

So, we can now output some message to the console but can we receive user input from it instead? Sure, use gets().

print("Enter your favorite fruit: ")
fruit = gets() # input your favorite fruit and press enter
puts("You entered #{fruit}")

Variables

Variables are awesome. They help us create dynamic code. The example below shows 2 variables, a string and an integer.

s = "i am a string"
i = 9

We declared 2 variables and gave them a value each. We can check their type by using is_a? or kind_of?:

s.is_a? Integer # false
s.is_a? String # 
 
i.kind_of? Integer # false
i.kind_of? String # true

The methods is_a? and kind_of? end in question marks. Its a Ruby coding convention which tells you that the method returns Boolean. How cool is that? Also, instead of declaring the two variables in new lines, we can do it in a single line by separating each with a comma:

s, i = "i am a string", 9

Methods

You will be using these almost all of the time. If you have some code that has use in multiple places, you could put that in a method. A method in Ruby is created by the def keyword. Below, we are defining a method with name say_hello that receives a parameter: name.

def say_hello(name)
  puts "Hello #{name}"
end
 
say_hello "Ruby" # "Hello Ruby"

Notice above that the parameter is embedded within the string itself: "Hello #{name}". To evaluate a variable, simply place it in the curly braces followed by hash #{ } and the variable will reveal its value.

You created a method and would like to output a value. Let’s say you created a Calculator app and would like to tell the sum of 2 variables. How would you do that? See the next example:

def add(a,b)
  return a+b
end
 
puts(add(10,15)) # 25
puts(add(2, add(10, add(10, 20)))) # 42

The return keyword sends the value outside the method. Its optional though, but I am not going to cover that and confuse you. We will stick with return for now. Allow me to show you something cool instead. Want to return multiple values from your methods? Simply separate them with a comma:

def define_name_age
  return "John", 20
end
 
# name will take the first return value: John
# age will take the second return value: 20
name, age = define_name_age 
 
puts(name) # John
puts(age) # 20

Arrays & Loops

Arrays are very useful because they can store more than one “variable”. In Ruby, there are several ways to create arrays:

# creates an array with 3 elements
fruits = ["apple", "orange", "banana"]
 
# also creates an array with 3 elements
fruits = "apple", "orange", "banana"
 
# also creates an array with 3 elements
fruits = %w(apple orange banana)
 
# also creates an array with 3 elements
fruits = []
fruits[0] = "apple"
fruits[1] = "orange"
fruits[2] = "banana"

Below are a few helpful Array methods:

fruits.length # 3
fruits.min # "apple"
fruits.max # "banana"
 
fruits[0] # "apple"
fruits[1] # "orange"
fruits[2] # "banana"
fruits[3] # nil
 
fruits.reverse # ["banana", "orange", "apple"]
fruits.pop # ["apple", "orange"]
fruits.insert 2, "banana" # inserts banana back at the last position
 
todays_fruits = "pear", "grape"
all_fruits = fruits + todays_fruits # ["apple", "orange", "banana", "pear", "grape"]

You created an array and would now like it to reveal its elements in an iterative fashion. You use a loop to do so. The idea behind a loop is quite simple: loop through a block of code for a given number of times. An example:

# prints out "apple", "orange" & "banana"
for i in fruits
  puts (i)
end
 
# also prints out "apple", "orange" & "banana"
fruits.each do |i|
  puts i
end

Control Structures

The if statement when satisfied, tells the interpreter to execute some part of code. It can be used with else or elsif constructs.

# creating fruits
fruits = ["apple", "orange", "banana"]
 
# example 1
# output: i haz banana
if fruits.include? "banana"
  puts "i haz banana"
end
 
# example 2
# output: i haz no pear
fruit = "pear"
if fruits.include? fruit
  puts "i haz #{fruit}"
else
  puts "i haz no #{fruit}"
end
 
# example 3
# output: i haz no pear
fruit = "pear"
if !fruits.include? fruit
  puts "i haz no #{fruit}"
elsif fruits.include? fruit
  puts "i haz #{fruit}"
end

The .include? method checks if the array has a value or not.

  1. In the first example, because the fruits array has a banana, the code inside if executes.
  2. In the 2nd example, since the array has no pear, execution enters the else block.
  3. Example #3 does the same thing as #2. What about the ! guy in if !fruits.include? fruit? That symbol makes the statement read: “If the fruits array does not include my fruit” – which is why the output is “i haz no pear”.

Another way of doing the same as shown previously:

fruit = "pear"
puts((fruits.include? fruit) ? "i haz #{fruit}" : "i haz no #{fruit}")

Let’s try something similar with the Case statement, which does the same thing but as conditions grow, it makes them easier to manage.

# method has_fruit
def has_fruit(fruit)
  case (fruit)
    when "apple"
      puts ("i haz 5 apples")
    when "orange"
      puts ("i haz 1 orange")
    when "banana"
      puts ("i haz 10 bananas")
    else puts ("i haz no #{fruit} in stock")
  end
end
 
has_fruit "apple" # i haz 5 apples
has_fruit "pear" # i haz no pear in stock

Classes

Okay, some of you must be dreading this moment. But, just like the previous topics we have covered, they are not going to be complex at all. Let’s figure out how to make a class. Since we have been dealing a lot with fruits, we will make a Fruit class.

class Fruit
  def gimme_fruit_names
    return ['apple', 'orange', 'banana']
  end
end

Carefully observe the code above. I have only wrapped my function with the class keyword. Until now, we have called the method directly. With Classes, you must create an instance to use their methods. I must tell the Fruit class that I need to use one of its methods and I can do that by instantiating it. So, let’s create an instance of Fruit class:

# create an instance of Fruit class
# f becomes into a Fruit object
f = Fruit.new
 
# f can now call the method gimme_fruit_names 
f.gimme_fruit_names # ['apple', 'orange', 'banana']

It was’t so hard, was it? We created an instance of the Fruit class using Fruit.new and assigned that instance to variable f. Then, we called the guy gimme_fruit_names living inside the class separated by the dot character.

We will now cover what’s called a Constructor and an instance variable. Wow, all these terminologies.

class Fruit
  # constructor
  def initialize(to_eat)
    puts "we just entered constructor"
 
    # instance variable: to_eat
    # visible to all methods inside a class
    @to_eat = to_eat
 
    # instance variable: fruits
    @fruits = ["apple", "orange", "banana"]
  end
 
  # function
  def is_available?
    # for-loop that traverses all elements of fruits array
    @fruits.each do |i|
      if (@to_eat == i)
        puts "We have a(n) #{i.capitalize} for you."
        return true
      end
    end
 
    puts "No #{@to_eat.capitalize}s buddy, come back again"
  end
end
 
fruit = Fruit.new("orange") # "we just entered constructor"
fruit.is_available?() # We have a(n) Orange for you.
 
fruit = Fruit.new("grape") # "we just entered constructor"
fruit.is_available?() # No Grapes buddy, come back again

The little guy initialize() is the constructor. What is this constructor, you might ask. A constructor is automatically called when we use the new method to create an object. It can take arguments but does not return any values. So, when we run the code fruit = Fruit.new("orange") all the lines of code inside initialize are executed.

Ok, what about the funny @ symbol preceding @to_eat and @fruits?? Preceding variable names with @ makes them instance variables. Instance variables always begin with @ and are visible to every method of the class. Even though @to_eat and @fruits were created in initialize when Fruit.new was called, they are being used in is_available?.

That’s all the programming we are going to do in this topic. There are many other concepts I would like to cover but this tutorial has become quite lengthy already. I am quite sure you are tired by now so let’s take a breather. But.. did you like this article? Post your comments below and let me know. Before I end this article, 2 important things you might want to know..

IDEs/Editors

I use Eclipse but there are many other choices you may find more suitable for your needs. I am listing some of them here:

  • Ruby in Steel
  • Sublime Text (recommended by Matt)
  • Eclipse
  • Aptana
  • RubyMine
  • TextMate
  • Notepad++
  • NetBeans (Ruby support has been discontinued with NetBeans 7)
  • RedCar

Running Ruby files from Shell

To run a ruby file (with .rb extension), just use the code ruby [filename].rb where [filename] is the name of the file you intend to run.

To show you an example, there are 3 files in the directory \Relevant Codes\Ruby. To run program.rb, I used the following code: ruby program.rb.

Subscribe for Relevant Codes newsletter to get awesome updates and articles delivered straight to your inbox.

Leave a Comment

{ 4 comments… add one }

  • Matt June 20, 2013, 9:17 am

    I also recommend Sublime Text for Ruby development. Great article.

    Reply
    • Anshoo Arora June 20, 2013, 1:38 pm

      Thanks Matt, and for the recommendation too. I have added Sublime Text to the list.

    • Anonymous June 23, 2013, 1:27 pm

      Anshoo where exactly Ruby is used , as we know Vbscript we use for QTP..

    • Anshoo Arora July 22, 2013, 11:09 am

      Ruby is just a scripting language, like VBScript; but it is completely Object Oriented and very dynamic. Ruby has a much greater scope than VBScript and most famous for Rails.