Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

ruby - How is each_with_object supposed to work?

I'm trying to figure out how each_with_object is supposed to be used.

I have a sum example that doesn't work:

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

I would assume that the result would be 6 ! Where is my mistake ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

each_with_object does not work on immutable objects like integer.

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

This is because each_with_object iterates over a collection, passing each element and the given object to the block. It does not update the value of object after each iteration and returns the original given object.

It would work with a hash since changing value of a hash key changes it for original object by itself.

(1..3).each_with_object({:sum => 0}) {|i,hsh| hsh[:sum] += i}
#=> {:sum => 6}

String objects are interesting case. They are mutable so you might expect the following to return "abc"

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

but it does not. This is because str += "a" returns a new object and the original object stays the same. However if we do

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

it works because str << "a" modifies the original object.

For more info see ruby docs for each_with_object

For your purpose, use inject

(1..3).inject(0) {|sum,i| sum += i} #=> 6
# or
(1..3).inject(:+) #=> 6

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...