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

Commit

Permalink
Inject vs each_with_object in ruby
Browse files Browse the repository at this point in the history
  • Loading branch information
Rajeev N B authored and JoelQ committed Apr 3, 2015
1 parent 1204dec commit 4c2b65c
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions ruby/inject_vs_each_with_object.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Inject vs each_with_object

## Inject

Inject takes the value of the block and passes it along.
This causes a lot of errors like.

```ruby
inject_array = ['A', 'B', 'C', 'D']

inject_array.inject({}) do |accumulator, value|
accumulator[value] = value.downcase
end

Output: 'IndexError: string not matched'
```

The above code causes 'IndexError: string not matched' error.

What you really wanted.

```ruby
inject_array = ['A', 'B', 'C', 'D']

inject_array.inject({}) do |accumulator, value|
accumulator[value] = value.downcase
accumulator
end

Output: => {"A"=>"a", "B"=>"b", "C"=>"c", "D"=>"d"}
```

## each_with_object

each_with_object ignores the return value of the block and passes the initial object along.

```ruby
array = ['A', 'B', 'C', 'D']

array.each_with_object({}) do |value, accumulator|
accumulator[value] = value.downcase
end

Output: => {"A"=>"a", "B"=>"b", "C"=>"c", "D"=>"d"}
```
One more thing which you can notice is the order of arguments to the block for each of the functions.

Inject takes the result/accumulator and then the iteratable value, whereas 'each_with_object' takes the value followed by the result/accumulator.

0 comments on commit 4c2b65c

Please sign in to comment.