Introducing Ruby

Extremely useful, and rather fun too!

Introducing Ruby

Ruby is a fun, different and interesting language. It is vaguely similar to Perl and its very widely used and hence a useful language to be familiar with. Getting started is simple and if you are acquainted with languages such as Python, you will be coding Ruby in no time.

So how about a quick introduction? Come on in and lets get started! This little tutorial will give you a quick start into writing Ruby code. There are tons of tutorials out there, and this one is based upon a few similar tutorials that Ive been through myself. The only assumption I will be making here is that you have Ruby installed. If you’re on a Linux system this is almost guaranteed to come pre-installed, so just fire up a terminal and type irb.

irb, or “Interactive Ruby Shell” lets us evaluate Ruby statements on the fly, so let start our Ruby-adventure by writing a Hello world app.

puts "Hello World"

Yep, that is all the code we need. Hit enter and you will get the predictable result along with a nil-value. The result of an expression in Ruby always returns nil, which is Ruby’s way of saying absolutely-positively-nothing.

Lets expand on our Hello World application a bit. Lets put it in a method. And while the irb is great for quickly testing code and expressions, I quite prefer to type it in a file. So quit the irb shell and create a file called hello_world.rb using your favorite code editor (I use and recommend vim) and type in the following code.

def hello
        puts "Hello World"
end
hello()

Save it, and run it by typing the folllowing.

ruby hello_world.rb

We have now defined a method labeled hello and we call it by writing hello(). Actually, we dont even need the parentheses when the method doesnt take any parameters, but I like to do it anyway. You are free to pick your own personal preference of course.

Speaking of parameters though, why not let our method take one?

def hello(name)
        puts "Hello #{name}!"
end
 
hello("Untouchab1e")

Running this piece of code will print out the given parameter. #{name} is the Ruby-way of inserting a variable into a string. The variable can also be manipulated like any other string, so how about improving our Ruby script a bit?

def hello(name= "World") #Setting default value for name
        puts "Hello #{name.capitalize}!" #Capitalizing the first letter of name.
end
 
hello("untouchab1e")
hello()

Running this will print out “Hello Untouchab1e” and “Hello World”, even though in the script we have not capitalized our initial parameter value. Magic?!

Now that we are fairly familiar with simple methods, lets put our method into a class and add additional methods. Then create an object of that class and run the methods.

class Hello
        def initialize(name = "World")
                @name = name #Instance variable, available for all methods of the class.
        end
        def say_hello
                puts "Hello #{@name}!"
        end
        def say_bye
                puts "Bye #{@name}, see you soon!"
        end
end
 
#Create a Hello object.
hello = Hello.new("Bob")
#Run the say_hello method
hello.say_hello()
#Run the say_bye method
hello.say_bye()

The comments in the code explain fairly simply what is going on here. We create an object and run methods that the class features.

How can we tell what methods a class supports though? If you are working with code others have written or you are unsure what you can do with built in methods, we can use the instance_methods function to see them all. In the case of our previous code example, we could try and run Hello.instance_methods() which would list all the methods for the Hello object, including the ones inherited. If you add the following line to the bottom of your code, you will see that we get a lot more than our two methods.

puts Hello.instance_methods()

If we only want to see the methods defined directly by our object, we can do that by specifying we dont want all indirect methods listed out by calling Hello.instance_methods(false).

We can then use the method respond_to? to see if our object understands what we want it to do. Add these lines to your code and see for yourself

puts hello.respond_to?("say_hello")
puts hello.respond_to?("say_dumbass")

The first line will return true, as its an actual method, while the second one will return false, as we never created a method by that name. Makes sense right?

Currently, once we set the value of the @name variable, its set for good. We cant change it. I suppose its not often you change your name but for the sake of user friendlyness and just the desire to be awesome, lets see if we cant do something about that.

class Hello
        #We make the name variable accessible, allowing us to manipulate it as we see fit.
        attr_accessor :name
        def initialize(name = "World")
                @name = name #Instance variable, available for all methods of the class.
        end
        def say_hello
                puts "Hello #{@name}!"
        end
        def say_bye
                puts "Bye #{@name}, see you soon!"
        end
end
 
#Create a Hello object.
hello = Hello.new("Bob")
#Run the say_hello method
hello.say_hello()
#Run the say_bye method
hello.say_bye()
#We decide to do a sex change, and hence want to go under a more appropriate name
hello.name="Claire"
hello.say_hello()

If you run the code now, you will see how we successfully changed the name from Bob to Claire. This is all thanks to the attr_accessor statement in the beginning of the class. It gives us the ability to manipulate the associated variable as much as we want. Neat, eh?

So far, we have only been dealing with a single name at a time. The name variable is a string object. Well, at least it becomes onet when it holds a string. How about we become a little more including and rewrite our program so that it can handle a list of names instead? Feel free to improvise with the code below to extend the functionality too! Hold on to your hat, as the code below is a bit more complex, but read the comments and you will cope with it rather nicely.

#!/usr/bin/env ruby
 
#Notice that I define the location of ruby above
#Similar to bash, Python, etc..
 
class ListHello
        #We are creating a variable namelist, and we want to manipulate it
        attr_accessor :namelist
 
        #Initialize
        def initialize(namelist = "World")
                #default value will just be World! Pretty safe woulndt you say?
                @namelist= namelist
        end
 
        #Lets say hi then!
        def say_hi
                #We should check if our list is empty, so lets make an if-statement
                if @namelist.nil?
                        puts "I have nothing to say!"
                elsif @namelist.respond_to?("each")
                #By checking if namelist responds to the "each" method, we determine whether its a list of names
                #or if it only contains one value, and as of such is a string.
                        @namelist.each do |name|
                                puts "Hello there, #{name}!"
                        end
                else
                        put "Hello #{@namelist}!"
                end
        end
 
        #Lets say bye, but in a sligthyl different manner..
        def say_bye
                #Again we check if our list is empty or if its actually a list or just a string.
                if @namelist.nil?
                        puts "I have no one to say bye to!"
                elsif @namelist.respond_to?("join")
                        #Lets list out all the names, separated by commas
                        puts "Farewell #{@namelist.join(", ")}, see you all soon!"
                else
                        puts "Farewell there #{@namelist}, see ya!"
                end
        end
end
 
if __FILE__ == $0
        #Lets get started by creating the ListHello object
        lh = ListHello.new
        #The name will be the default "World" here..
        lh.say_hi
        lh.say_bye
        #Change the name to hold a single name
        lh.namelist = "Stastny"
        lh.say_hi
        lh.say_bye
        #Now lets change the name to hold a whole bunch of names
        lh.namelist = ["Landeskog", "Varlamov", "Stastny", "Hejduk", "Duchene"]
        lh.say_hi
        lh.say_bye
        #Finally, lets clear it out!
        lh.namelist = nil
        lh.say_hi
        lh.say_bye
end

The comments should hopefully bring clarity to what is going on here. But its important to not here that we never specify what datatype the variable namelist is. This is why we need to check. If it only holds a single string then Ruby handles it as a string, but the moment it holds list objects, then Ruby also considers the variable a list type. The code above is a good framework to play with though, and Im sure you can make a pretty awesome hello world app out of it!

Notice how we check if its the file is being used as an executable or if its included as a library.

if __FILE__ == $0

In the code we also make use of if-statements and loops. Simple enough, right?

That wraps up our little tutorial. If you understand what you’ve just forced yourself through, I would say that you have a rough idea about how this whole thing works. Once you got the syntax down, writing Ruby code isnt much different from Perl or Python.

So I hope you enjoyed our little adventure and of course, if you have any questions, problems, comments or tricks, feel free to comment!

See you around!

 

 

« »