[RAILS] [Ruby] From the basics to the inject method

inject method

Reference: https://docs.ruby-lang.org/ja/latest/method/Enumerable/i/inject.html

What is Enumerable in the first place?

module. A mix-in for repeating classes. The following are famous friends (instance methods).

Reference: https://docs.ruby-lang.org/ja/latest/class/Enumerable.html

In Ruby, thanks to the ʻEnumerable` module, you can use methods with convenient iterations.

Basic usage

ary = [1,2,3,4,5]
ary.inject(1){ |sum, n| sum + n }
# => 16

--The return value of each process in the block is in sum. --The method argument goes into the initial value (the block argument of the first process). --Repeat until the last element, and the return value of the last block becomes the total return value.

,,,Hard to understand.

Let's make it easy to understand.

ary = [1,2,3,4,5]
ary.inject(1) do |sum, n| 
  puts sum
  sum + n 
end
 
=begin
=>1 (Initial value specified in the argument of inject"1"Enters sum)
=>2 (Initial value (sum)+Sum of the first element (n) of the array)
=>4 (The return value (2) of the previous process is in sum+Second element sum)
=>7 (Omitted below)
=>11
=>16 (overall return value)
=end

Can you imagine it somehow? This is ** folding **.

By the way, if you omit the method argument (hoge part of ʻinject (hoge)`), the first element of the array will be set to the initial value.

ary = [1,2,3,4,5]
ary.inject do |sum, n| 
  puts sum
  sum + n 
end
 
=begin
=>1 
=>3 
=>6 
=>10 
=>15 (overall return value)
=end

What makes me happy

With a proper understanding, you can write complex processes in an easy-to-understand manner. Since the processing inside the block can be repeated by folding, it can be written shorter than the ʻeach` method.

In other words, it is often used for refactoring iterations.

Let's write some practical code below.

Actual usage

Get the sum of the arrays

For each

sum = 0
ary = [100,200,300,42,52]
ary.each { |n| sum += n }
puts sum
# =>694

In case of inject

ary = [100,200,300,42,52]
sum = ary.inject { |s, n| s += n }
puts sum
# =>694

One line has decreased. Refreshing.

Recommended Posts

[Ruby] From the basics to the inject method
[Ruby basics] How to use the slice method
How to use Ruby inject method
From Java to Ruby !!
Iterative processing of Ruby using each method (find the sum from 1 to 10)
[Ruby] Method to easily get the receiver type .class
Ruby algorithm (inject, method definition)
What I did in the version upgrade from Ruby 2.5.2 to 2.7.1
How to use the form_with method
[Ruby] Method to count specific characters
[Ruby basics] split method and to_s method
[Ruby] How to use any? Method
I tried to explain the method
Introduction to Ruby (from other languages)
The road from JavaScript to Java
Ruby basics
[Android, Java] Method to find the elapsed date from two dates
[Ruby on Rails] Use the resources method to automatically create routes.
Ruby basics
Easy to understand the difference between Ruby instance method and class method.
[Challenge CircleCI from 0] Learn the basics of CircleCI
[Ruby] Obtaining even values ​​using the even? Method
Investigate the replacement from Docker to Podman.
[Rails] How to use the map method
[Java] How to use the toString () method
I wanted to add @VisibleForTesting to the method
I was addicted to the roll method
Ruby from the perspective of other languages
I tried to build Ruby 3.0.0 from source
Extract characters from Ruby strings slice method
From terminal to Ruby (standard input / output)
How to find the cause of the Ruby error
[Ruby] Summary of class definitions. Master the basics.
If it is Ruby, it is efficient to make it a method and stock the processing.
Ruby to_s method
A memorandum to clean up the code Ruby
[heroku deployment procedure ③] From Ruby version specification to deployment and access to the application (complete)
Migration from Eclipse to IntelliJ (on the way)
Method to search
[Ruby] How to use gsub method and sub method
The story of introducing Ajax communication to ruby
A fledgling engineer learned JUnit from the basics
[Ruby] I want to do a method jump!
[Ruby] slice method
[Ruby] end_with? method
[Ruby] Method memorandum
Basics of Ruby
When you want to use the method outside
Output of how to use the slice method
I tried to get the distance from the address string to the nearest station with ruby
About the method
[Ruby] How to calculate the total amount using the initialize method and class variables
[Ruby] Code to display the day of the week
[Ruby basics] I tried to learn modules (Chapter 1)
[Ruby] What is the slice method? Let's solve the example and understand the difference from slice!
How to use the replace () method (Java Silver)
[Ruby] I want to make an array from a character string with the split method. And vice versa.
Read the official Dagger2 documentation to understand the basics
[Ruby] Exclude duplicate elements with the uniq method.
[Ruby] initialize method
Ruby build method