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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
We can get the value of an element using its key, by writing hash_name[key]
.
|
|
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
|
|
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.
|
|
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
|
|
We can access element using index/key and print each element using each
method.
|
|
The code will print
|
|
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
.
|
|
Using nil
When we use values that are nil
, it will be treated like false
, the code won’t be executed, and vice versa.
|
|
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
|
|
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
|
|
THe example using parameter and argument is shown below
|
|
by passing argument to the method, e.g. greeting("Mina", 3)
, we’ll get output
|
|
Method using default argument
We can use default value of argument in parameter method like
|
|
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
|
|
Method using symbols
Also we can use empty symbol like
|
|
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.
|
|
As a convention, we add a question mark ?
at the end of the method name if it returns a boolean value
|
|
By adding control flow, you can use return
multiple times.
|
|
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
|
|
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
|
|
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.
|
|
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.
|
|
Initialize Method
The initialize
method can be defined just like other instance methods. Our previous code will look like:
|
|
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
|
|
In the book.rb
put only Book class
|
|
And in the index.rb
, where the program is executed, put these lines
|
|
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
|
|
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
.
|
|
The child class
has access to all the instance variables and methods of the parent class
.
|
|
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.
|
|
Super
To avoid duplications during initializing the name
and price
in the child class Food
, We use super
|
|
After using super
, the code will be
|
|
Adding Instance methods
We also can add instance methods to the child class
|
|
Overiding
Since we want to display calorie
in the info
method. We will be overriding the info
method in the Food
class.
|
|
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.
|
|
Sample Project
back to Ruby tutorial index