Last modified: Thu Aug 16 2018 22:49:02 GMT+0800 (Malay Peninsula Standard Time)

Chapter 2. Ruby Objects and Methods

Ruby is an object-oriented language. Everything (yes, everything) in Ruby is an Object. This means all other classes including Array, Fixnum and String are inheriting all methods from Object unless they are overridden in their own definition. In this chapter, we are going to see how are the predefined methods help us in our programming.

2.1 .first and .last Methods

Instead of accessing an array by remembering the position, we can use .first to access the first element and .last to access the last element of the array. Figure 2.1.1 shows the result of the value in third, first and last position of the array being printed.


Figure 2.1.1: Printing value in third, first, and last position the array a using IRB.

2.2 .include? Method

We usually use a loop to check whether a value is in the array. In Ruby, we can use .include? to check if the value that we want to find is in the array. Figure 2.2.1 shows the result of the checking two different values.


Figure 2.2.1: Result of checking two values in the array using IRB.

2.3 .inspect Method

In my opinion, .inspect is the most useful method for Ruby on Rails developer. Most of the time, we may face an issue where we do not know what and how the return parameter will return. We may get an array that contains multiple array. At this point, we can use .inspect method to inspect what is in the array. Figure 2.3.1 shows a sample array that contains multiple arrays within an array. By using the .inspect method, we can print everything in the array and inspect by ourselves.


Figure 2.3.1: A sample array that contains multiple arrays within an array.

2.4 .to_str Method

.to_str method is a method that will convert any object to string. It is commonly use when you are trying to merge an integer to string. Figure 2.4.1 shows a sample program that merge two integers to a string. In Ruby, plus sign, +, can be used to add two numbers or combine two string.


Figure 2.4.1: Sample program of .to_str method in IRB.

2.5 .pluck Method

.pluck is a method that grab the attributes in the database we want. The return values will be string by default. Table 2.5.1 shows a database table for users.

Table 2.5.1: Sample Database Table

id firstname lastname age gender
1 Andrew Hui 22 m
2 Christine Lee 31 f
3 Matthew Nguyen 22 m

To get a list of firstname from users table, we can use the command below.

User.pluck(:firstname)

The result of the operation above will be [‘Andrew’, ‘Christine’, Matthew’].

We can use SQL DISTINCT in the method. Assume that we are trying to get distinct ages of all users, we can use the command below.

User.pluck(‘DISTINCT age’)

The result of the operation above will be [‘22’, ‘31’].

We can always select more than one columns. If we are trying to get the firstname and lastname attributes, we can use the command below.

User.pluck(:lastname, :firstname)

The result of the operation above is shown below. Do note that the arrange of each attribute matter.

[[‘Hui’, ‘Andrew’], [‘Lee’ ,‘Christine’], [‘Nguyen’, Matthew’]]

2.6 .gsub! Method

.gsub is a method that is able to substitute a word in a string. The operation is illustrated in Figure 2.6.1.


Figure 2.6.1: Sample program of .gsub! method in IRB.

2.7 .all Method

.all is a method that grab all attributes in the database. The return values will be string by default. Table 2.7.1 shows a database table for users.

Table 2.5.1: Sample Database Table

id firstname lastname age gender
1 Andrew Hui 22 m
2 Christine Lee 31 f
3 Matthew Nguyen 22 m

The code below is retrieving every single available row and attributes from the users database table. Do note that the name of the model is in capital letter.

User.all

The result of the operation above is at shown below. The order of attributes are based on the arrange of the attribute in the database.

[[‘1’, ‘Andrew’, ‘Hui’, ‘22’, ‘m’], [‘2’, ‘Christine’, ‘Lee’ , ‘31’, ‘f’], [‘3’, Matthew’, ‘Nguyen’, 22, ‘m’]].

The equivalent of the code in SQL is as below.

SELECT * FROM Users

2.8 .joins Method

.joins is a method that joins database based on the reference key or foreign key. Before a joins operation is able to carry out, you have to make sure that you have all the relationship of the model setup correctly. Table 2.8.1 shows a database table for users.

Table 2.8.1: Sample users Database Table

id firstname lastname age gender
1 Andrew Hui 22 m
2 Christine Lee 31 f
3 Matthew Nguyen 22 m

Table 2.8.2 shows a database table for comments database table that contains a foreign key, user_id.

Table 2.8.2: Sample comments Database Table

id title body user_id
1 Great! sample body 1 1
2 Love it! sample body 2 1
3 Never get it sample body 3 2

To join comments and users table, we use the command below. Do note that comments table contains a user’s foreign key, user_id.

Comment.joins(:user)

The code below is retrieving every single rows with all attributes from the comments database table and join it with users table that matches the integer value in user_id attribute. The result of the operation above is at shown below. The order of attributes are based on the arrange of the attribute in the database.

[[‘Great!’, ‘sample body 1’, ‘1’, ‘1’, ‘Andrew’, ‘Hui’, ‘22’, ‘m’], [‘Love it!’, ‘sample body 2’, ‘1’, ‘2’, ‘Christine’, ‘Lee’ , ‘31’, ‘f’], [‘Great!’, ‘sample body 3’, ‘2’, ‘Christine’, ‘Lee’ , ‘31’, ‘f’]]

The equivalent of the code in SQL is as below. There is no difference between using uppercase or lowercase for the first letter in the table’s name (Comments vs comments). However, you have to use the exact table name (singular vs plural).

SELECT * FROM Comments, Users WHERE Comments.user_id = Users.id

2.9 .min Method

.min is a method that will return the minimum value in an array. The operation is illustrated in Figure 2.9.1.


Figure 2.9.1: Sample program of .min method in IRB.

2.10 .max Method

.max is a method that will return the maximum value in an array. The operation is illustrated in Figure 2.10.1.


Figure 2.10.1: Sample program of .max method in IRB.

2.11 .minmax Method

.minmax is a method that will return the minimum and maximum value from an array in the form of array. The operation is illustrated in Figure 2.11.1.


Figure 2.11.1: Sample program of .minmax method in IRB.

2.12 .min_by Method

.min_by is a method that will return the minimum value in a hash specified by the condition. Assuming that we have a hash, friends, with two parameters: name and age, the code is shown as below.

friends = {'kitty' => 12, 'lily' => 31, 'moh' => 23}

We would like to find who is the youngest. In this case, we can use the method .min_by. To find the person who is the youngest in the hash, we use the command below.

friends.min_by { |name, age| age }

The operation is illustrated in Figure 2.12.1.


Figure 2.12.1: Sample program of .min_by method in IRB.

2.13 .max_by Method

.max_by is a method that will return the maximum value in a hash specified by the condition. Assuming that we have a hash, friends, with two parameters: name and age, the code is shown as below.

friends = {'kitty' => 12, 'lily' => 31, 'moh' => 23}`

We would like to find who is the youngest. In this case, we can use the method .max_by. To find the person who is the youngest in the hash, we use the command below.

friends.max_by { |name, age| age }

The operation is illustrated in Figure 2.13.1.


Figure 2.13.1: Sample program of .max_by method in IRB.

2.14 .minmax_by Method

.max_by is a method that will return the minimum and maximum value in a hash specified by the condition. Assuming that we have a hash, friends, with two parameters: name and age, the code is shown as below.

friends = {'kitty' => 12, 'lily' => 31, 'moh' => 23}

We would like to find who is the youngest. In this case, we can use the method .minmax_by. To find the person who is the youngest in the hash, we use the command below.

friends.minmax_by { |name, age| age }

The operation is illustrated in Figure 2.14.1.


Figure 2.14.1: Sample program of .minmax_by method in IRB.

results matching ""

    No results matching ""