Compiled Chronicles

A software development blog by Angelo Villegas

Let’s try Ruby in 30 minutes

A Brief History

Ruby is a dynamic, reflective, object-oriented, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro “Matz” Matsumoto in Japan.

Ruby syntax is inspired by Perl with Smalltalk-like features and was also influenced by Eiffel and Lisp. It supports multiple programming paradigms, including functional, object oriented, and imperative. It also has a dynamic type system and automatic memory management. Therefore, it is similar in varying degrees to Smalltalk, Python, Perl, Lisp, Dylan, and CLU.

Introduction

This is a Ruby tutorial that should take no more than 30 minutes to complete. The topic of how to install Ruby on your system will not be tackled in this tutorial.

Interactive Ruby Shell

We won’t really need an IDE playing with Ruby, coding in interactive sessions like this is a better way to learn the language.

Opening up Interactive Ruby (IRB)

  • For OS X, open up Terminal and type irb
  • For Linux, open up a shell and type irb
  • For Windows, open fxri from the Ruby section of your Start Menu.

By doing so, the very first line you’ll see is this:

irb(main):001:0>

If that line appears after you typed irb, it means you are successful accessing the Interactive Ruby Shell. Now type "Hello World!" and it will display

irb(main):001:0> "Hello World"
=> "Hello World!"

What Happened?

The second line is just IRB’s way of telling the result of the last expression we gave. It doesn’t do anything as we only gave IRB a string. If we want to actually do something then let’s try the most common way to write the very first program you’ll write when learning a new language: Hello World! .

irb(main):002:0> puts "Hello World!"
Hello World!
=> nil

puts is the basic command to print something out in Ruby, similar to PHP’s echo and JavaScript’s document.write.

But what’s the => nil part?

That’s the result of the expression. puts always returns nil, Ruby’s saying it returned nothing.

Defining A Method

Ruby methods are used to bundle one or more repeatable statements into a single unit. Ruby methods’ syntax are very similar to functions in other programming languages such as PHP, C, and JavaScript to name a few.

Ruby syntax is inspired by Perl with Smalltalk-like features and was also influenced by Eiffel and Lisp.

Method names should begin with a lowercase letter. If you begin a method name with an uppercase letter, Ruby might think that it is a constant and hence can parse the call incorrectly.

Methods should be defined before calling them, otherwise Ruby will raise an exception for undefined method invoking.

Method Syntax

def method_name [( [arg [= default]]...[, * arg [, &expr ]])]
  expr..
end

Why did you use two spaces? Standard is four spaces or one tab with four space width right?

Note: Code layout is pretty much up to you; indentation is not significant but using two-character indentation in Ruby will make you friends in the community if you plan on distributing your code because Ruby is using two spaces per indentation level (aka soft tabs), no hard tabs. You can learn more style guide here: Ruby Style Guide

def sayHi
  puts "What's your name(s)?"
  names = gets.strip()
  if names.nil?
    puts "..."
  elsif names.respond_to?("each")
    names.each do |name|
      puts "Hello #{name}!"
    end
  else
    puts "Hello #{names}!"
  end
end

Come on! Is that even legal?

I’ve gone ahead and wrote a proper method with a bit of input/output functions. What the method does is it will take your name and output “Hello” plus your name in it.

Of course i’ll explain bit by bit what the codes are and what they do individually. It’s a bit English compared to other programming languages, if you have a background in programming i’m sure you have an idea of what the method does.

def sayHi

The code def sayHi starts the definition of the method. It tells Ruby that we’re defining a method, that its name is sayHi. The next line is the body of the method, almost the same line we saw earlier: puts "Hello World!"; but this time instead of saying Hello World!, we wrote What's your name(s)?.

puts "What's your name(s)?"

This is a question asking your name. If you can remember, IRB waited for you until you wrote your name, this is because it is waiting for an input.

names = gets.strip()

This block of code will gets the keys we typed in (your name in this example) and the following .strip will strip out leading and trailing whitespace.

  if names.nil?
    puts "..."

As you can see, there’s an if statement. This statement is a conditional statement that performs an action based on different decisions. On our code, we asked if names is nil?. The answer, if yes, is for our code to print out ... on the terminal.

  elsif names.respond_to?("each")
    names.each do |name|
      puts "Hello #{name}!"
    end

Our code now becomes a bit trickier, next stop is elsif. In this condition, we will check if names can respond_to? the method each. If the names object responds to each, it is something that you can iterate over, so iterate over it and greet each person in turn. This is called a loop statement, specifically, a for loop.

  else
    puts "Hello #{names}!"
  end

If the two conditions before was not met, we fall back to the last condition. What’s the #{name}? That is Ruby’s way of inserting something into a string, a format. The object between the braces is turned into a string (if it isn’t one already) and then appended into the outer string at that same point. You can also use this to make sure that a string is properly capitalized, in this case, a name:

puts "Hello #{name.capitalize}!"

Finally, the last line end tells Ruby we’re done defining the method. Ruby’s response => nil tells us that it knows we’re done defining the method.

Running The Method

Still in IRB, let’s call our method: sayHi.

irb(main):016:0> sayHi
What's your name(s)?
Angelo
Hello Angelo!
=> nil

Fibonacci

Another common code is the Fibonacci sequence. This is common just like the Hello World!; it’s a bit more tricky than just printing a string though.

If you don’t already know, in mathematics, the Fibonacci sequence are the numbers in the following integer sequence:

$latex 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …&s=3$

or (often, in modern usage):

$latex 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …&s=3$

The next number is found by adding up the two numbers before it.

The first two numbers in the Fibonacci sequence are 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence, and each subsequent number is the sum of the previous two.

  • The 2 is found by adding the two numbers before it (1+1)
  • Similarly, the 3 is found by adding the two numbers before it (1+2),
  • And the 5 is (2+3),
  • and so on!

It’s pretty easy right?

Can you figure out the next few numbers?

def fibonacci
  puts "How many sequence?"
  sequence = Integer(gets) rescue 10
  a, b, c = 0, 0, 1
  for x in 0..sequence
    a = b
    b = c
    c = a + b
    puts "#{a}"
  end
end

Let’s break the code, first we def fibonacci to define a method; then printed a question “How many sequence?”.

Now, have you noticed something? Our getter is not just a simple gets.strip() like before but we changed it to Integer(gets) rescue 10. It means we need to get the integer value and return a sequence 10 if it’s not.

Next is we assigned multiple objects: a, b, c = 0, 0, 1. This means a = 0, b = 0, and c = 1.

  for x in 0..sequence
    a = b
    b = c
    c = a + b
    puts "#{a}"
  end

This block is a loop statement or, more specifically, for loop. It means it will reiterate as long as the expression was met.

for variable [, variable ...] in expression [do]
   code
end

In our code’s case, our expression is 0..sequence with variable x and sequence is the number we just keyed. Now, here’s the body of our code that actually calculates the Fibonacci sequence.

    a = b
    b = c
    c = a + b

each subsequent number is the sum of the previous two.

To get our answer, we need to add the first two numbers first and print it out using the puts method. If you’ve made a Fibonacci code before on a different language, you’ll probably notice that the code’s logic is just the same.

Conclusion

That’s Ruby, this quick tour is only the beginning, there are lots of things in Ruby that needs to be explored and I’m pretty sure you won’t stop here. If you really want to learn Ruby, don’t forget to study it’s style guide (linked above). I hope this short post has left you wanting to learn more of Ruby.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *