Featured image of post Ruby Basic Operation

Ruby Basic Operation

Learn basic of Ruby: variables, string, integer, self-assignment, comparison and condition operator, looping, method

back to Ruby tutorial index

Variables

Variables are a way to access memory locations using an alias. Storing data to a variable is called assignment. Variables have multiple components: name, data, and type.

To use a variable, we must define it first. Like variable_name = value. In Ruby, = does not mean that the values are equal. It means to assign the value on the right to the variable on the left.

Variable Scope

Let us investigate this code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
post_count = 10

def report
  post_count = 5
  puts post_count
end

report

puts post count

The code above will print 5 and then 10. Why? because post_count in method levl and outside not affect each other. If we want to have global variable that visible everywhere throghout the program, just put the dolar sign like $log_level.

Self Assignment

We can use shorthand like

1
2
3
4
5
x += 10
x -= 10
x *= 10
x /= 10
x %= 10

String Concatenation

Combining strings is known as string concatenation. So if we put code like puts "Hello" + "Ruby", it will produce output like "Hello Ruby"

String Interpolation

There’s a way to include the value of a variable inside a string. We can replace a variable with the value we assigned and include it in the string by inserting #{variable_name}, as shown below

1
2
3
name = "Mina"
age = 4
puts "Hello, my name is #{name}, I am #{age} year old"

There’s one thing to be careful of with string interpolation. It can only be used in double quotes ". If it’s used with single quotes ', the variable won’t be replaced with it value.

Arrays

We can use arrays to manage a group of data all at once. We can create an array as follows: [value1, value2, ...]. Each value in an array is known as an element. Using arrays, you can manage a collection of data as one group.

Example

Here are examples of array usage

1
2
3
4
5
6
7
8
# assignment of string array
names = ["Zahra", "El", "Mina"]
# assignment of integer array
numbers = [3,4,5]
# array assignment of mix data type
things = ["John", 17, "married"]
# print an array element
puts "My name is #{names[0]}"

For each element of an array, a number is given like 0, 1, 2, .... These number are known as index number.

Each method

The each method allows you to access each element of an array in a temporary variable, and apply the same code to it. For Instance, let’s try to print each name in the previous example

1
2
3
names.each do |name|
  puts "My name is #{name}"
end

Hashes

Like arrays, hashes are used to manage multiple groups of data. The difference is that hashes use keys instead of index numbers. With hashes, a key is paired with a value to form one element.

Example

1
2
3
4
# arrays
arrs = [value1, value2, value3]
# hashes
hashs = {key1 => value1, key2 => value2, key3 => value3}

We can get the value of an element using its key, by writing hash_name[key].

1
2
user = {"name" => "Mina", "age" => 4}
puts user["name"]

The value of an element in the hash can be updated using hash_name[key]= new_value. If the key doesn’t exist yet, the element will be added to hash.

Symbols in hashes

The key of a hash can be written by prepending (adding in front) the key with a colon : instead of enclosing them with quote ' or double qoutes ". The way of writing :name is known as symbol. We can use the shorthand syntax of writing the hash key when using symbols. :key => can be abbreviated to key:. The sample of hashes syntax are recap below

1
2
3
4
5
6
# strings as keys
person1 = {"name" => "Mina", "age" => 4}
# symbols as keys
person2 = {:name => "Zahra", :age => 5}
# symbols as keys (shorthands)
person3 = {name: "El", age: 6}

nil

There is a special value in Ruby known as nil to express that a value doesn’t exist. Since nil means “nothing”, puts nil will print nothing.

1
2
user = {name: "Mike", age: 32} # asssignment
puts user[:height] # will return nil

We learn how to use nil in condition operator later.

Array with Hash element

We can use hashes as well as strings and numbers for array elements. Keep in mind that we often add a newline between each of the hash elements for better readability, as shown below

1
2
3
4
students = [
  {name: "Mina", age: 4},
  {name: "Zahra", age: 5}
]

We can access element using index/key and print each element using each method.

1
2
3
students.each do |student|
  puts "hello, my name is #{student.name}, I'm #{student.age} years old"
end

The code will print

1
2
"Hello, my name is Mina, I'm 4 years old"
"Hello, my name is Zahra, I'm 5 years old"

Condition Operators

Comparison Operators

Operators like >, <, >=, <=, ==, != are known as comparison operators.

Logical Operators

We can use logical operators to express AND or OR. && is used for AND, and will return true only when both condition are true. The mathematical expression of 10 < x 30 will be expressed as x > 10 && x < 20 will be expressed as x > 10 && x < 20 in Ruby.

If statement

The comparison and logical operators usually used in if statement.

1
2
3
4
5
6
7
if condition1
  # some code
elsif condition2
  # some code
else condition3
  # some code
end

Using nil

When we use values that are nil, it will be treated like false, the code won’t be executed, and vice versa.

1
2
3
4
5
6
biju1 = {name: "Kurama", age: 234}
if biju1[:age]
  puts "#{biju1[:name]} is #{biju1[:age] year old}"
else
  puts "#{biju1[:name]}'s age is unknown}"
end

Method

A method lets us combine multiple lines of code into a single unit. For example, we can define the introduce method to do two thinks

1
2
3
4
def introduce
  puts "Hello"
  puts "I am Mina"
end

We can pass values to a method when we call it. These values are known as arguments, and can be used inside methods.

To pass an argument to a method, you have to define it with a variable to receive it. This variable in particular is called a parameter.

The relation between argument and paramaters is depict code below

1
2
3
4
5
def method_name(parameter)
  # some code
end

method_name(argument)

THe example using parameter and argument is shown below

1
2
3
4
def greeting(name, age)
  puts "hello, my name is #{name}"
  puts "I am #{age} years old"
end

by passing argument to the method, e.g. greeting("Mina", 3), we’ll get output

1
2
"hello, my name is Mina"
"I am 3 years old"

Method using default argument

We can use default value of argument in parameter method like

1
2
3
4
def greeting2(name = "foo", age = 99, is_married = false)
  puts "hello, my name is #{name}"
  puts "I am #{age} years old"
end

If all parameters have default value like code above, then we can call method directly without passing any arguments like greeting2() or we can omit the parentheses greeting2. and the method will process default value.

Using parameter key(s) in greeting2 method is an optional. We can put this greeting2(name = "Mina Zahra") or like this greeting2("Mina Zahra"). And we should put the argument in correct order event we put parameter key. Run this method like greeting2(age = 33, name = "John") will lead to misleading result like

1
2
"hello, my name is 33"
"I am John years old"

Method using symbols

Also we can use empty symbol like

1
2
3
4
def greeting3(name:, age:, is_married: false)
  puts "hello, my name is #{name}"
  puts "I am #{age} years old"
end

In the method above, the usage of parameter key when we pass the argument is mandatory but you should not to put the pair of key and argument in correct orders. You can write like this greeting3(age: 77, name: "Jane") and it will print the correct result.

Method with return

To send a value to the origin of the method call, we use the return statement. By writing return value, the value can be returned and be used outside of the method.

1
2
3
4
5
6
# example return value
def add(a,b)
  return a + b
end
sum = add(3,4)
puts sum

As a convention, we add a question mark ? at the end of the method name if it returns a boolean value

1
2
3
4
# example return bool
def negative?(number)
  return number < 0
end

By adding control flow, you can use return multiple times.

1
2
3
4
5
6
def judge(score)
  if score > 80
    return "Good Job"
  end
  return "You can do better"
end

Getting Input

To receive input from the console, we use the gets.chomp method. gets.chomp will stop the execution, then wait for the input.

Let’s make simple console app. Put all these lines into file called hello.rb

1
2
3
puts "Enter your name:"
name = gets.chomp
puts "Hello #{name}"

run the file ruby hello.rb, enter your name and TADA your first console app in Ruby created !

Because the value received from gets.chomp will be string, even if 98 is entered, it will be treated as string "98". To convert it to integer, we use to_i method.

Let’s improve our previous app

1
2
3
4
5
6
puts "Enter your name:"
name = gets.chomp
puts "What is your birthyear:"
birthyear = gets.chomp.to_i
puts "Hello #{name}"
puts "your age is #{2022-birthyear}"

Class

For example we want to make book rental app. In programming, by treating each book as an object, we can easily manage multiple books. To create an object, you first need to prepare its blueprint. In programming terms, this blueprint is commonly known as the class, and each object is known as an instance.

1
2
3
class Book
  attr_accessor :title, :author
end

Class Naming Convetion

  • Class names start with a capital letter or using PascalCase
  • Capitalize abbreviations: XMLParser, JSONRequest

Instance Methods

The methods defined inside a class are called instance method, as they are to be called from an instance. For instance below we created a instance method called description to put all together book information in a single sentence.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Book
  attr_accessor :title, :author
  def description
    puts "Book titled '#{self.title}' is written by #{self.author}"
  end
end

book1 = Book.new
book1.title = "Sang Pemimpi"
book1.author = "Andre Hinata"

book1.description

Initialize Method

The initialize method can be defined just like other instance methods. Our previous code will look like:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Book
  attr_accessor :title, :author
  def initialize(title:, author:)
    self.title = title
    self.author = author
  end
  def description
    puts "Book titled '#{self.title}' is written by #{self.author}"
  end
end
...

self in code above is referring to instance variable.

Separating Files

Let us move the Book class to a different file called book.rb to keep each file simple and manageable. The structure of files will look like

1
2
3
book_app
|- book.rb
└- index.rb

In the book.rb put only Book class

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Book
  attr_accessor :title, :author
  def initialize(title:, author:)
    self.title = title
    self.author = author
  end
  def description
    puts "Book titled '#{self.title}' is written by #{self.author}"
  end
end

And in the index.rb, where the program is executed, put these lines

1
2
3
4
5
book1 = Book.new
book1.title = "Sang Pemimpi"
book1.author = "Andre Hinata"

book1.description

Class Inheritance

Let assume that we run an online restaurant that sell foods, Then we should create Menu as an object.

The product class can be written as

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Menu
  attr_accessor :name, :price
  def initialize(name:, price:)
    self.name = name
    self.price = price
  end
  def info
    return "#{self.name} $#{self.price}"
  end
end

Creating a class based on another class is known as inheritance. Child class is referring to the new class, while parent class is referring to the class used as a base. You can use inheritance as follow: class ChildClass < ParentClass.

1
2
3
class Food < Menu
  
end

The child class has access to all the instance variables and methods of the parent class.

1
2
3
menu1 = Food.new(name: "Plecing", price: 2)
puts menu1.name
puts menu1.info

Adding instance variable to child

To add an instance variable to the child class, we can again use attr_accessor. In the example below, the Food class has the calorie instance variable in addition to the name and price variables defined in the Menu class.

1
2
3
class Food < Menu
  attr_accessor :calorie
end

Super

To avoid duplications during initializing the name and price in the child class Food, We use super

1
2
3
4
5
6
7
8
class Food < Menu
  def initialize(name:, price:, calorie:)
    self.name = name
    self.price = price
    self.calorie = calorie
  end
  ...
end

After using super, the code will be

1
2
3
4
5
6
7
class Food < Menu
  def initialize(name:, price:, calorie:)
    super(name: name, price: price)
    self.calorie = calorie
  end
  ...
end

Adding Instance methods

We also can add instance methods to the child class

1
2
3
4
5
6
7
class Food < Menu
  attr_accessor :calorie
  ...
  def calorie_info
     return "#{self.name} is #{self.calorie}kcal"
  end
end

Overiding

Since we want to display calorie in the info method. We will be overriding the info method in the Food class.

overriding method

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Food < Menu
  attr_accessor :calorie
  
  def initialize(name:, price:, calorie:)
    super(name: name, price: price)
    self.calorie = calorie
  end
  
  def info
    return "#{self.name} $#{self.price} (#{self.calorie}kcal)"
  end
  
  def calorie_info
     return "#{self.name} is #{self.calorie}kcal"
  end
end

Define a class method

We can define a class method like def ClassName.method_name. Note that unlike instance method, we have to put the class name before the method name.

1
2
3
4
5
6
7
class Menu
  ...
  def Menu.discount_day?
    today = Date.today
    return today.sunday?
  end
  ...

Sample Project


back to Ruby tutorial index

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy