Inject Notes Day 1 Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

what does inject do?

A

Inject is an enumerable that allows you to pass elements in an array through block of code using two parameters. if you don’t specify the acc then it will be the first ele in the array and the following param will be the second ele in the array. Inject will return a mutated acc.

product of all ele in an array
p [11, 7, 2, 4].inject { |acc, el| acc * el } # => 616

minimum value in an array
p [11, 7, 2, 4].inject do |acc, el|
    if el < acc
        el
    else
        acc
    end
end # => 2
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

can you set a default acc when using inject?

A

yes you can!

[11, 7, 2, 4].inject(0) do |acc, el|
    if el.even?
        acc + el
    else
        acc
    end
end # => 6
How well did you know this?
1
Not at all
2
3
4
5
Perfectly