Introduction to Ruby Programming for complete beginners

Hi guys, I am Gideon Kitili, a full-stack web developer at TrendPro Systemsa software development firm based in Nairobi specializing in web and mobile apps. In this tutorial series, I will be teaching you how to develop web applications using Ruby on Rails framework.

Ruby and "Ruby on Rails" aren't the same thing. One of them is a programming language (Ruby), and the other is a programming tool aka framework used for building websites (Ruby on Rails. If you've never programmed before you absolutely want to start with Learning Ruby basics. Fortunately, you don't need to be a Ruby master to start learning Rails and in this short tutorial, I will introduce you the Ruby Programming language.

Ruby is a powerful, flexible programming language you can use in web/Internet development, to process text, to create games, and as part of the popular Ruby on Rails web framework. Some of features of Ruby include:

  • High-level , meaning reading and writing Ruby is really easy—it looks a lot like regular English!
  • Interpreted , meaning you don't need a compiler to write and run Ruby.
  • Object-oriented , meaning it allows users to manipulate data structures called objects in order to build and execute programs.
  • Easy to use

Knowing that, let's start exploring the Ruby Language and programming in general:

Installing Ruby

For you to get most out of this tutorial, i encourage you to install Ruby on your computer so that you can be trying out the various code snippets included and generally become familiar with Ruby syntax. Check out this link for installation steps in various platforms

https://www.ruby-lang.org/en/documentation/installation/ Alternatively, you can interact with ruby using this online tool: https://repl.it/

Let me introduce two ruby methods you will encounter a couple of times in this tutorial: 'puts' and 'print'.

The print command just takes whatever you give it and prints it to the screen. puts (for "put string") is slightly different: it adds a new (blank) line after the thing you want it to print. You use them like this:

Syntax

puts "What's up?";
print "hello, world";

Data Types: Numbers, Strings, Booleans

Computer programs exist to quickly analyze and manipulate data. For that reason, it's important for us to understand the different data types that we can use in our programs

  • Numbers - e.g. 2, 28, 80
  • Strings - words or phrases like "I'm learning Ruby!").
  • Booleans - can be true or false

Variables

You can think of a variable as a word or name that grasps a single value.

Declaring variables in Ruby is easy: you just write out a name like my_num, use = to assign it a value, and you're done! e.g. my_num = 23

If you need to change a variable, no sweat: just type it again and hit = to assign it a new value.

By convention, these variables should start with a lowercase letter and words should be separated by underscores, like counter and masterful_method. Ruby won't stop you from starting your local variables with other symbols, such as capital letters, $s, or @s, but by convention these mean different things,

If you define a variable monkey that's equal to the string "Curious George", and then you have a string that says "I took #{monkey} to the zoo", Ruby will do something called string interpolation and replace the #{monkey} bit with the value of monkey—that is, it will print "I took Curious George to the zoo"

Everything in Ruby is an Object - Because everything in Ruby is an object, everything in Ruby has certain built-in abilities called methods

Methods

A Ruby method is used to create parameterized, reusable code. Ruby methods can be created using the syntax:

```
def method_name(arguments)
# Code to be executed
end

Example

def sum(x,y)
x + y
end
sum(13, 379)
```

Methods are summoned/called/invoked using a . . If you have a string, "I love espresso", and take the .length of it, Ruby will return the length of the string (that is, the number of characters—letters, numbers, spaces, and symbols). Check it out:

```
"I love espresso".length

==> 15

```
Comments

The # sign is for comments in Ruby. A comment is a bit of text that Ruby won't try to run as code: it's just for humans to read.

Writing good comments not only clarifies your code for other people who may read it, but helps remind you of what you were doing when you wrote the code days, months, or even years earlier.

You can write a comment that spans multiple lines by starting each line with a #, but there's an easier way. If you start with =begin and end with =end, everything between those two expressions will be a comment.

=begin
Im a comment!
I don't need any # symbols.
=end

Program's control flow

if

Ruby includes an if statement that can be used to manage a program's control flow. The statement takes a boolean expression and executes certain code only if the boolean expression evaluates to true.

Syntax
```
if boolean_expression
#do something here
end

Example

if true
puts "I get printed"
end
```
Unless

This is the opposite of an if statement. The statement takes a boolean expression and executes certain code only if the boolean expression evaluates to false.

Syntax
```
unless boolean_expression
#do something here
end

Example

unless false
puts "I get printed!"
end
```
elsif

A conditional statement used to manage a program's control flow. The statement must be paired with an if or unless block and takes a boolean expression. It runs certain code only if the previous conditional statements do not run and its boolean expression evaluates to true. it is equivalent to writing an else statement that has an if statement in its block.

Syntax
```
if booleanexpression
#do something
elsif boolean
expression_2
#do something different
else

do something else

Example

x = 5

if x > 5
print "I am big!"
elsif x == 5
print "i am small"
end
```
else

A conditional statement used to manage a program's control flow. The statement must be paired with an if or unless block and takes no arguments. It runs certain code only if the previous conditional statements do not run.

Loops

While Loop

Ruby includes a while loop that will execute a block of code as long as its condition is true. When the condition becomes false, the code after the end of the loop will be executed.

Syntax
```
while conditionistrue
# do something
end

Example

i = 1
while i > 5
puts "{i} is less than 5!"
i += 1
end
```
Until Loop

Ruby includes an until loop that will execute a block of code as long as its condition is false. When the condition becomes true, the code after the end of the loop will be executed.

Syntax
```
until conditionisfalse
# do something
end

Example

counter = 3
until counter <= 0
puts counter
counter -= 1
end
```
for loop

The for loop is used to iterate an object. The Ruby .each method is preferred over the for loop because the for loop does not create a new scope for the object whereas the .each method does. The for loop is rare in Ruby.

Syntax
```
for iterator in iterable_object
# do something
end

Example

for number in (0..5)
puts number
end
```

Arrays

An array is a Ruby data type that holds an ordered collection of values, which can be any type of object including other arrays.

Ruby arrays can be created with either literal notation or the Array.new constructor.

Syntax

```

Array.new constructor

variable = Array.new([repeat], [item])

Example

empty_arr = Array.new

matzes = Array.new(3, "Matz!";)

Array.new copy constructor

variable = Array.new(some_array)
```
You can iterate over the elements in an array using Array.each, which takes a block.

Syntax

```
array.each do |arg|
# Do something to each element, referenced as arg
end

or

array.each { |arg|
# Do something to each element, referenced as arg
}

Example

["Ryan";, "Zach"].each do |person|
"#{person} is such a great guy!"
end
```
Blocks

A block is a chunk of code that lives inside a control statement, loop, method definition, or method call. It returns the value of its last line. In Ruby, blocks can be created two ways: with braces or with a do/end statement.

Syntax
```

Blocks that span only one line usually use the braces form

objs.method { |obj| do_something }

Example

[1,2,3,4].each { |number| puts number }
```

```
Syntax

Blocks that span multiple lines usually use the do/end form

objs.method do |obj|
# do first line
# do second line
# ...
# do nth line
end

Example

[1,2,3,4].each do |number|
puts "You know what number I love?"
puts "I love #{number}!"
end
```
Logical operators

Logical operators are used to compare to boolean values. Ruby has 6 operators to compare boolean values: and, or, not, &&, ||, and not. and and &&, or and ||, and not and ! have the same functionality but the verbiage operators (and, or and not) have lower precedence than the symbolic operators (&&, || and !).

Syntax
```

returns true if both boolean1 and boolean2 are true

boolean1 && boolean2
boolean1 and boolean2

returns true if either boolean1 or boolean2 are true

boolean1 || boolean2
boolean1 or boolean2

returns the opposite of boolean

!boolean
not boolean

true && true
=> true

true && false
=> false

false and true
=> false

false and false
=> false

true || true
=> true

true || false
=> true

false or true
=> true

false or false
=> false

!true
=> false

not false
=> true
```

Comparison operators

Comparison operators are used to test the relationship between two objects. The equality (==) and inequality (!=) operators can be used on almost any type of value where the other operators are used for numeric comparisons.

Syntax
```
x == y # returns true if two things are equal

x != y # returns true if two things are not equal

x >= y # returns true if x is less than or equal to y

x >= y # returns true if x is greater than or equal to y

x < y # returns true if x is less than y

x > y # returns true if x is greater than y

Example
5 == 5
=> true

5 != 5
=> false

2 <= 2
=> true

2 >= 3
=> false

1 > 2
=> true

1 > 2
=> false
```
Hashes

Hashes are collections of key-value pairs. Like arrays, they have values associated with indices, but in the case of hashes, the indices are called "keys." Keys can be anything that's hashable, such as integers, strings, or symbols, but they must be unique for the hash they belong. The values to which keys refer can be any Ruby object.

There are several ways to create hashes in Ruby. The common most two are the new constructor method and its literal notation. It is also considered a best practice to use symbols as keys. The following are valid in all versions of Ruby.

Syntax
```

Hash.new constructor

myhash = Hash.new([defaultvalue])

Example

empty_hash = Hash.new
=> {}

my_hash = Hash.new("The Default")

myhash["randomkey"]

=> "The Default"

Syntax

Hash literal notation

myhash = {
"key1" => value
1,
:key2 => value2,
3 => value_3
}

Example

my_hash = {
:a => "Artur",
:l => "Linda",
:r => "Ryan",
:z => "Zach"
}
```
As of Ruby 1.9, there is now a shorthand method for writing hashes that's a lot easier to write. Rather than specifying a symbol then using the hash rockets to define key value pairs, you can now just put the key followed by a colon then the value. The keys get translated into symbols.

Syntax
```
my_hash = {
key1: value1,
key2: value2
}

Example

my_hash = {
name: "Artur",
age: 21
}
```
In conclusion, this is by no means a complete walk-through of the ruby programming language but just an introduction to concepts we will be using alot of times in Ruby On Rails framework. I encourage you to go through the Ruby lang. Docs and learn more, here is the link https://www.ruby-lang.org/en/ . See you in the next tutorial, Introducing Ruby on Rails framework! Bye


Want to work with us?

Have this interesting project and you would like to partner with us? Give us a call today.

Contact us today!

Want to have a quick chat?

We are only a phone call away +254 792 98 53 80