Get familiar with the Ruby programming language

RubySyntax

Ruby is one of my favorite programming languages. Everything in Ruby is an object. In this article, I want to give a brief introduction to the Ruby syntax.

Strings

In Ruby, you can create string objects in the following ways:

first_name = "Mary"
last_name = String.new 

Now first_name can use the built-in methods available for the String class. For example, we can say first_name.length and we will get 4. Length returns the number of characters contained in that variable. In addition to the length method, the String class has other methods such as upcase, downcase, capitalize.

Numbers

In Ruby, you will encounter 2 types of classes that deal with numbers, floats and fixnums.

Float

Numbers that contain decimals are treated as floats in Ruby. To create a float, you can use:

tax_rate = 8.25
total_amount = 1234.67 

Fixnum

If you need to use integer numbers, you will use fixnum. The good thing about Ruby is that you don’t have to declare the class type. You can just assign any value to your variable and Ruby will handle it.

work_days = 5
work_days.class # Fixnum   

In the above example, typing work_days.class returned “Fixnum” which is the class use to hold integer values.

Array

The official Ruby documentation defines it as, “Arrays are ordered, integer-indexed collections of any object.” You can create Array variables with the following syntax:

a = Array.new
b = [1, 2.3, "test"]

In the above example, a is created by calling the new method on the Array class. b on the other hand is created by using the literal constructor. To get the first item in b, you can use b[0]. Since Array are zero index based, 0 represents the first item in the array.

Hash

A hash is a dictionary-like collection. It is made up of keys and values. The key must be unique. Take a look at the following examples:

h1 = Hash.new
h2 = { "Dallas" => 1, "Houston" => 2, "San Antonio" => 3 }

The h1 variable was created using the new method and h2 was created using the literal constructor. To get the value of the key “Dallas” in h2, you can type h2[“Dallas”]. To get the keys only, you can use h2.keys and this will return an array with only the keys. Similar to the keys method, you can get the values with h2.values. The hash class has a lot of methods that I will go into more detail in a future article.

I hope you find this quick introduction to the Ruby programming language helpful.