Back to Tutorials
Tips6/8/2025

Ruby & Ruby on Rails : Inject

injectrailsruby

We're going to talk about Enumerable#inject ! Inject is super cool and if you don't use it in your code, then you should start. Really.

I used to do this kind of thing :

hash = {}
%w(one two three).each do |number|
  hash[number] = number
end
# => {"one"=>"one", "two"=>"two", "three"=>"three"}

Where I could just use inject !

result = %w(one two three).inject({}) do |hash, number|
  hash[number] = number
  hash
end
# => {"one"=>"one", "two"=>"two", "three"=>"three"}

EDIT : There is a better way than inject to deal with this kind of situation : Enumerable#each_with_object

%w(one two three).each_with_object({}) { |number, hash| hash[number] = number }
# => {"one"=>"one", "two"=>"two", "three"=>"three"}

Thanks Gee-Bee :)


Basically, you can 'inject' anything. A Hash {}, an Array [], a number... Here are a few more examples :

Array :

result = %w(one two three).inject([]) { |arr, number| arr << number; arr }
# => ["one", "two", "three"]

# or more succinctly thanks to Gee-Bee
result = %w(one two three).inject([], :<<)
# => ["one", "two", "three"]

Sum :

result = [1, 2, 3].inject(0) { |sum, number| sum + number }
# => 6

# or more succinctly thanks to Gee-Bee
[1,2,3].inject(0, :+)
# => 6

Do you like to use Inject ? Did you know about it ? Let me know in the comments ;)

Comments

Loading comments...

Level Up Your Dev Skills & Income 💰💻

Learn how to sharpen your programming skills, monetize your expertise, and build a future-proof career — through freelancing, SaaS, digital products, or high-paying jobs.

Join 3,000+ developers learning how to earn more, improve their skills, and future-proof their careers.

Ruby & Ruby on Rails : Inject | Devmystify