Skip to content
This repository was archived by the owner on Aug 16, 2024. It is now read-only.

Commit 4c2b65c

Browse files
Rajeev N BJoelQ
authored andcommitted
Inject vs each_with_object in ruby
1 parent 1204dec commit 4c2b65c

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

ruby/inject_vs_each_with_object.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Inject vs each_with_object
2+
3+
## Inject
4+
5+
Inject takes the value of the block and passes it along.
6+
This causes a lot of errors like.
7+
8+
```ruby
9+
inject_array = ['A', 'B', 'C', 'D']
10+
11+
inject_array.inject({}) do |accumulator, value|
12+
accumulator[value] = value.downcase
13+
end
14+
15+
Output: 'IndexError: string not matched'
16+
```
17+
18+
The above code causes 'IndexError: string not matched' error.
19+
20+
What you really wanted.
21+
22+
```ruby
23+
inject_array = ['A', 'B', 'C', 'D']
24+
25+
inject_array.inject({}) do |accumulator, value|
26+
accumulator[value] = value.downcase
27+
accumulator
28+
end
29+
30+
Output: => {"A"=>"a", "B"=>"b", "C"=>"c", "D"=>"d"}
31+
```
32+
33+
## each_with_object
34+
35+
each_with_object ignores the return value of the block and passes the initial object along.
36+
37+
```ruby
38+
array = ['A', 'B', 'C', 'D']
39+
40+
array.each_with_object({}) do |value, accumulator|
41+
accumulator[value] = value.downcase
42+
end
43+
44+
Output: => {"A"=>"a", "B"=>"b", "C"=>"c", "D"=>"d"}
45+
```
46+
One more thing which you can notice is the order of arguments to the block for each of the functions.
47+
48+
Inject takes the result/accumulator and then the iteratable value, whereas 'each_with_object' takes the value followed by the result/accumulator.

0 commit comments

Comments
 (0)