Ruby inject with index and brackets

What is the use of these brackets?

It's a very nice feature of ruby. I call it "destructuring array assignment", but it probably has an official name too.

Here's how it works. Let's say you have an array

arr = [1, 2, 3]

Then you assign this array to a list of names, like this:

a, b, c = arr
a # => 1
b # => 2
c # => 3

You see, the array was "destructured" into its individual elements. Now, to the each_with_index. As you know, it's like a regular each, but also returns an index. inject doesn't care about all this, it takes input elements and passes them to its block as is. If input element is an array (elem/index pair from each_with_index), then we can either take it apart in the block body

sorted.each_with_index.inject(groups) do |group_container, pair|
  element, index = pair

  # or
  # element = pair[0]
  # index = pair[1]

  # rest of your code
end

Or destructure that array right in the block signature. Parentheses there are necessary to give ruby a hint that this is a single parameter that needs to be split in several.

Hope this helps.


lines = %w(a b c)
indexes = lines.each_with_index.inject([]) do |acc, (el, ind)|
  acc << ind - 1 if el == "b"
  acc
end

indexes # => [0]

Tags:

Ruby