String 对象上的“tap"方法不返回预期结果 [英] The 'tap' method on String object doesn't return expected result

查看:33
本文介绍了String 对象上的“tap"方法不返回预期结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在对String"类型的对象使用tap"方法时遇到了一个有趣的问题.

I ran in to an interesting problem while using the 'tap' method on objects of type 'String'.

"abc".tap { |o| o = "xyz" } # this line returns "abc" instead of "xyz"

tap"方法适用于其他类型的对象.

The 'tap' method works on objects of other types.

[].tap { |o| o << "xyz" } # this line returns ["xyz"] as expected

我在 Windows XP 上使用 Rails 2.3.2 和 Ruby 1.8.6.

I am using Rails 2.3.2 and Ruby 1.8.6 on Windows XP.

我在这里遗漏了什么?

更新 1:我解决了这个问题.这是我的使用错误.在第一个场景中,我将值重新分配给块参数而不是修改它.我能够重写代码并获得预期的结果.

Update 1: I resolved this issue. It was an usage error on my part. In the first scenario I was re-assigning the value to the block parameter instead of modifying it. I was able to rewrite the code and get the expected result.

"abc".tap { |o| o.replace "xyz" }

更新 2:此处使用的代码仅用于演示问题.我的实际代码不是这样的.

Update 2: Code used here is just to demonstrate the problem. My actual code does not look like this.

推荐答案

Object#tap 总是返回执行块后传入的原始对象,即使块返回不同的东西.

Object#tap always returns the original object passed into it after executing the block, even if the block returns something different.

这里的好处是你可以在链的中间放置tap并测试一个对象的值,而无需修改原始值.

The benefit here is that you can put tap into the middle of a chain and test the value of an object without modifying the original value.

这意味着如果您将abc"传递给 tap,它将执行该块并返回abc".由于范围界定,您对 o 的分配没有任何意义.同样,如果您将一个空数组传递给 tap,它将返回一个空数组.但是,在您的第二个示例中,您修改了原始值.<<等修改原件的操作或 gsub!或者同样会在返回之前修改对象,因此您会得到不同的值.

This means that if you pass "abc" into tap, it'll execute the block and return "abc". Your assignment to o doesn't mean anything due to scoping. Likewise, if you pass an empty array into tap, it would return an empty array back. However, in your second example, you modified the original value. Operations that modify the original such as << or gsub! or likewise will modify the object before its returned, therefore you get a different value back.

查看http://moonbase.rydia.net/mental/blog/programming/eavesdropping-on-expressions 有关如何使用 tap 的一些更酷的示例.不要将它用于分配或修改,否则你会得到不稳定的结果.

Check out http://moonbase.rydia.net/mental/blog/programming/eavesdropping-on-expressions for some more cool examples about how to use tap. Don't use it for assignment or modification or you'll get back wonky results.

更新:对于您的编辑,为什么这可以解决您的问题?我不明白为什么当您可以在对象本身上调用替换时,为什么要调用 tap 来执行替换.Tap 为您提供了什么好处?

Update: To your edit, why does that resolve your issue? I don't understand why you'd call tap to do a replace when you can just call replace on the object itself. What benefit is tap providing you?

这篇关于String 对象上的“tap"方法不返回预期结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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