each_with_object 应该如何工作? [英] How is each_with_object supposed to work?

查看:28
本文介绍了each_with_object 应该如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚应该如何使用 each_with_object.

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

我假设结果是 6 !我的错误在哪里?

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

推荐答案

each_with_object 不适用于整数等不可变对象.

each_with_object does not work on immutable objects like integer.

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

这是因为 each_with_object 迭代一个集合,将每个元素和给定的对象传递给块.每次迭代后它不会更新对象的值,而是返回原始给定对象.

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 对象是有趣的例子.它们是可变的,因此您可能会期望以下内容返回abc"

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} # => ""

但事实并非如此.这是因为 str += "a" 返回一个新对象而原始对象保持不变.但是如果我们这样做

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"

它有效是因为 str <<<;"a" 修改原始对象.

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

有关详细信息,请参阅 each_with_object

For more info see ruby docs for each_with_object

出于您的目的,请使用 inject

For your purpose, use inject

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

这篇关于each_with_object 应该如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆