Can someone explain the use in the real world of a common injection language in Ruby?

I am working on learning Ruby and came across an injection. I am on the verge of understanding this, but when I'm the type of person who needs real world examples to learn something. The most common examples I come across are people who use injection to add the sum of a range (1..10) that I could care less about. This is an arbitrary example.

What will I use in a real program? I am studying, so I can go to Rails, but I do not need to have a web-oriented example. I just need something that has a purpose, I can wrap my head.

Thanks to everyone.

+5
source share
5 answers

(1 ) - (), .

().

inject() :

[1, 2, 3, 4].inject(0) {|memo, num| memo += num; memo} # sums all elements in array

[1, 2, 3, 4] memo ( ). , .

[1, 2, 3, 4].inject(0) {|memo, num| memo += num} # also works

inject() :

result = 0
[1, 2, 3, 4].each {|num| result += num}
result # result is now 10

inject() . convert() [['dogs', 4], ['cats', 3], ['dogs', 7]] {'dogs' => 11, 'cats' => 3}.

[['dogs', 4], ['cats', 3], ['dogs', 7]].inject({'dogs' => 0, 'cats' => 0}) do |memo, (animal, num)|
  memo[animal] = num
  memo
end

:

[['dogs', 4], ['cats', 3], ['dogs', 7]].inject(Hash.new(0)) do |memo, (animal, num)|
  memo[animal] = num
  memo
end

, inject() :

result = Hash.new(0)
[['dogs', 4], ['cats', 3], ['dogs', 7]].each do |animal, num|
  result[animal] = num
end
result # now equals {'dogs' => 11, 'cats' => 3}
+5

inject "" reduce. , Enumerable ( ) .

, Enumerable, map. -, .

:

range.inject {|sum, x| sum += x}

range . () , . , , .inject, .

SQL-. , , , , - inject :

cart_total = prices.inject {|sum, x| sum += price_with_tax(x)}

, Enumerable , , , Enumerable , . inject , , .

+7

, , - eBay, . , +, .

0

ActiveRecord - . scoped , , . , , - params:

search_params = params.slice("first_name","last_name","city","zip").
  reject {|k,v| v.blank?}

search_scope = search_params.inject(User.scoped) do |memo, (k,v)|
  case k
  when "first_name"
    memo.first_name(v)
  when "last_name"
    memo.last_name(v)
  when "city"
    memo.city(v)
  when "zip"
    memo.zip(v)
  else
    memo
  end

(: NO-, , , .)

0

All Articles