Parsing .inject vs .each_with_object

I know that each_with_objectdoes not work with immutable objects like integer.

for instance (1..3).each_with_object(0) {|i,sum| sum += i} #=> 0

We can fix this by injection, and the amount will be 6. Fine!

Take another example

("a".."c").each_with_object("") {|i,str| str += i} # => ""

This will not work, because when we do str+=i, we create a new object

Instead we need to do

("a".."c").each_with_object("") {|i,str| str << i} # => "abc"

Why does this happen, when I do the injectfollowing two ways, I get strange results

("a".."c").inject("") {|i,str| str += i} # => cba

("a".."c").inject("") {|i,str| str << i} # => ERROR

Why is the first print abcin reverse order? And why the second mistake?

, .each_with_object , inject (, integer), .inject , .each_with_object? - ?

+4
1

abc ?

. . # .

i str .

$ ruby -e '("a".."c").inject("") {|i,str| puts "i   = #{i}"; puts "str = #{str}"; ret = str += i; puts "ret = #{ret}\n\n"; ret }'
i   = 
str = a
ret = a

i   = a
str = b
ret = ba

i   = ba
str = c
ret = cba

i - , . str - . , . . - , - .

, .

$ ruby -e 'puts ("a".."c").inject("") {|sum,i| sum += i}'
abc

, , . str , .

$ ruby -e 'puts ("a".."c").inject("") {|sum,i| sum + i}'
abc

?

Ruby 2.0.0 2.2.4. .

$ ruby -e 'puts ("a".."c").inject("") {|i,str| str << i} # => ERROR'
cba

$ ruby -v
ruby 2.2.4p230 (2015-12-16 revision 53155) [x86_64-darwin15]
+2

Source: https://habr.com/ru/post/1652503/


All Articles