It's been about 4 months since I changed my job to a web contract development company that mainly handles Ruby on Rails. Even though I am a beginner, I am having a hard time assigning to the project and having a good time every day. I will summarize the Ruby methods that I think I will not use often during development!
--20200531 Corrected based on the comments received.
if A control structure that realizes conditional branching that does not require explanation. Evaluate with true or false and branch the process to be executed.
if conditional expression
true processing for if
elsif conditional expression
True processing for elsif
else
Handling of false
end
each A method to get the elements of an array in an iterative form. Rails uses it to get DB records in order.
[1, 2, 3].each do |i|
p i
end
output
1
2
3
map This is also similar to the each method, but It is used when specifying columns when retrieving DB records.
For example, if you have the following table
Users table
id |name | age | sex |
1 |Test Ichiro| 20 |Man|
2 |Test Hanako| 18 |woman|
3 |Test Jiro| 15 |Man|
You can specify the column and retrieve it in this way.
Users.all.map(&:age)
output
[20, 18, 15]
Get the id etc. of the table by specifying the column, This is useful for browsing the associated table. It is also often used in combination with the Where method.
where It is used when searching by specifying columns and data when retrieving records from the DB. If a table similar to map exists, you can get it as follows.
Users.where(age: 15)
output
id |name | age | sex |
3 |Test Jiro| 15 |Man|
first Gets the first record in a DB that has multiple records. If a table similar to map exists, you can get it as follows.
Users.first
output
id |name | age | sex |
1 |Test Ichiro| 20 |Man|
present?,blank?,nil? present ?: true if the value exists, false if it does not exist. When evaluating an array, if it is [], it will be nil and false. blank ?: True if there is no value. nil ?: True if the value of the variable is nil or no value.
It is often used when there is only one conditional branch by if. Conditional branching can be done with one line, and I personally think it is smart.
Conditional expression?true processing:Handling of false
count It counts DB records and uses them for pagination. If a table similar to map exists, you can get it as follows.
Users.count
output
3
Ruby 2.7.0 Reference Manual [Introduction to Ruby] Easy-to-understand explanation of how to use authenticity judgment present?
Recommended Posts