[RUBY] [Rough commentary] I want to marry the pluck method

It is sudden…

① Imagine a "colleague who can work tremendously" near you. ② Your "wife". Or think of an "ideal woman (male)".

A method that merges the two. I can work tremendously, yet cheerful and soft. That is the "pluck method" introduced this time.

(... I'm sorry I'll do it seriously)

Overview

This article

  1. What kind of method is pluck?
  2. When can pluck be used?

I will explain about. (* This article is useless for those who have already mastered the pluck method.)

What kind of method is pluck?

In conclusion, __ "get the value of a column in an array" __ method.

Let's take a table as an example.

users table (id, name, age)

id name age
1 ken 21
2 takuya 22
3 masato 29
4 kouta 24
5 hirokatsu 23
6 yuuhei 28
7 takumi 25
8 akihito 26

For example, if you have a table like this, you can use the pluck method to

users_controller.rb


@users = User.pluck(:id)

#Output result below
@users = [1, 2, 3, 4, 5, 6, 7, 8]

In this way, by setting __model name.pluck (column name) __, the contents of that column could be obtained as an array.

You can also specify a second argument ...

users_controller.rb


@users = User.pluck(:id, :name) #Specify name as the second argument

#Output result below
@users = [ [1, "ken"],[2, "takuya"],[3, "masato"],[4, "kouta"],
[5, "hirokatsu"],[6, "yuuhei"],[7, "takumi"],[8, "akihito"] ]

It is also possible to pass multiple arguments in this way and get it as an array. Even if you pass the 3rd and 4th arguments, you will get it as an array in the same way.

By the way, since it is an array, the acquisition method is slightly different,

users_controller.rb


@users = User.pluck(:id, :name) #Specify name as the second argument


@users[0][1] = "ken" #First array[1,"ken"]Because it is the second element of"ken"Get
@users[3][0] = 1  #4th array[4,"kouta"]Get 1 because it is the first element of

You can get the contents like this.

What you can do with the pluck method

So what can you do with the pluck method?

You can check if a particular record exists in a column

For example, if you want to find out if there is 24-year-old data in the User model,

users_controller.rb


User.where(age: 24).exists?
# => true

You can get it by doing the above, but if you use the pluck method

users_controller.rb


User.pluck(:age).include?(24)
# => true

You can get it with an expression like this: __ "... No, which one is fine?" __, but for these two I use pluck. I'll explain the reason next.

Data acquisition speed is improved

At first glance, the two formulas above look the same. However, the processing being performed and the number of data being acquired are completely different.

users_controller.rb


User.where(age: 24).exists?

↓ Here is the query (instruction for SQL) issued at this time ↓

MySQL


User Exists? (0.6ms)  SELECT 1 AS one FROM `users` WHERE `users`.`age` = 24 LIMIT 1
=> true

So what happens when you use the pluck method?

users_controller.rb


User.pluck(:age).include?(24)

↓ Click here for the issued query (command to SQL) ↓

MySQL


(0.5ms)  SELECT `users`.`age` FROM `users`
=> true

Do you see that it's obviously short? The processing time is also different by 0.1 milliseconds.

In the former, we are investigating "whether there is a 24-year-old user", whereas The latter is looking at "whether there is data for 24 years in the user's age".

In other words, by using pluck __ You can get only the columns you need, which means that your query will be shorter and faster __.

The more data you have, the wider the difference in processing speed. For those who say, "I made a portfolio, but the processing is somewhat sluggish ...", why not review the description of data acquisition?

Summary

① The pluck method is the __ "get the value of a certain column as an array" __ method (2) By using pluck, in some cases, useless query issuance is suppressed and __ processing speed is improved __

I hope you can understand the goodness of the pluck method even a little ... Thank you for watching until the end.

Recommended Posts

[Rough commentary] I want to marry the pluck method
I tried to explain the method
I want to expand the clickable part of the link_to method
I want to call a method and count the number
I want to use the sanitize method other than View.
I wanted to add @VisibleForTesting to the method
I was addicted to the roll method
I want to pass the argument of Annotation and the argument of the calling method to aspect
I want to output the day of the week
[Ruby] I want to do a method jump!
I want to var_dump the contents of the intent
When you want to use the method outside
I want to truncate after the decimal point
I want to get the value in Ruby
I want to call a method of another class
[Java] I want to calculate the difference from the date
I want to embed any TraceId in the log
I want to judge the range using the monthly degree
I want to know the answer of the rock-paper-scissors app
I want to display the name of the poster of the comment
I want to dark mode with the SWT app
I want to be aware of the contents of variables!
I want to return the scroll position of UITableView!
I want to simplify the log output on Android
I want to add a delete function to the comment function
Rspec: I want to test the post-execution state when I set a method on subject
What is the pluck method?
I want to convert characters ...
[Beginner] I want to modify the migration file-How to use rollback-
[Rails] [bootstrap] I want to change the font size responsively
I want to use screen sharing on the login screen on Ubuntu 18
(´-`) .. oO (I want to easily find the standard output "Hello".
I want to bring Tomcat to the server and start the application
I want to change the log output settings of UtilLoggingJdbcLogger
I want to use the Java 8 DateTime API slowly (now)
I want to create a form to select the [Rails] category
I want to put the JDK on my Mac PC
I want to give a class name to the select attribute
I want to recursively search the class list under the package
I want to distinct the duplicated data with has_many through
I want to transition to the same screen in the saved state
I want to narrow down the display of docker ps
I want to return multiple return values for the input argument
[Ruby] I want to reverse the order of the hash table
I want to temporarily disable the swipe gesture of UIPageViewController
I want to pass the startup command to postgres with docker-compose.
I want to simplify the conditional if-else statement in Java
How to use the link_to method
I want to give edit and delete permissions only to the poster
How to use the include? method
How to use the form_with method
I want to create a chat screen for the Swift chat app!
I want to understand the flow of Spring processing request parameters
I want to use FormObject well
I want to return to the previous screen with kotlin and java!
The story of Collectors.groupingBy that I want to keep for posterity
I want to convert InputStream to String
[Eclipse] I want to open the same file twice [Split editor]
I tried to understand how the rails method "redirect_to" is defined
The story I wanted to unzip
I want to limit the input by narrowing the range of numbers