ivan ivan - 1 month ago 8
Ruby Question

I need explanation of method inject

I am trying to figure out how inject method works

Can someone explain this

def mysort
djeca.order(name: :asc).inject([]) { |sum, c| sum += c.mysort}.uniq
end


mysort
is method of model class
Books


In controller I call method mysort :

@mybooks= Books.find_by(name: 'renesansa')
@mybookss= @mybooks.leaf_wms

Answer
djeca.order(name: :asc).inject([]) { |sum, c| sum += c.mysort}.uniq

is equivalent to

sum = []
djeca.order(name: :asc).each{|c| sum = sum + c.mysort}
sum.uniq

Adding arrays is actually concatening, so your code just appends all the c.mysort into an array.

If I understand it correctly, you could also write :

djeca.order(name: :asc).map{|c| c.mysort}.flatten.uniq

Depending on your audience, you might want to write one or the other. Note that you don't need to assign a value to sum in the inject block, it is done automatically.

(1..10).inject(0){|mem,i| mem += i}
#=> 55

(1..10).inject(0){|mem,i| mem + i}
#=> 55
Comments