返回 Ruby 中对象的产量的方法
Ruby 中是否有一种方法可以返回传递给对象的块的内容?
例如,如果我想将一个对象放入数组中怎么办?
在理想的世界中,我们会做(我正在寻找的):
"string".reverse.upcase.something{ |s| send(s) }
它将返回一个带有我的对象的数组,相当于:
send("string".reverse.upcase)
如果我有我的对象开始,并且在更复杂的情况下可能会变得混乱,那么它是不可链接的场景。
因此 something
方法将返回块的评估,例如 Array#map
,但仅适用于一个元素。
Is there a method in Ruby that returns the content of the block passed on to an object?
For example, what if I have an object which I want to put in an array?
In an ideal world, we would do (what I'm looking for):
"string".reverse.upcase.something{ |s| send(s) }
which would return an array with my object, as equivalent to:
send("string".reverse.upcase)
which isn't chainable if I have my object to start with and can get messy in more complex scenarios.
So the something
method would return the evaluation of the block, like Array#map
, but for one element only.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不知道有这样的内置功能,但你可以轻松地自己完成
:
I don't know of such a thing built-in but you can easily do it yourself:
gives
在最初的问题提出六年后,Ruby 2.5.0 引入了
Object#yield_self
,然后在 Ruby 2.6 中缩短为#then
:例如:
Six years after the original question, Ruby 2.5.0 introduced
Object#yield_self
, then shortened in Ruby 2.6 as#then
:For example:
您是否在寻找 Object.tap ?
Are you looking for Object.tap ?
我有时希望标准库中有类似的功能。例如,名称可以是
with
或with_it
(使用新名称重复先前的代码)
用法示例:
与以下内容相反:
虽然后者更容易理解,但前者具有在我看来,保持变量
list
和head
范围以及对x
的赋值的好处更加清晰(对x< /code> 必须插入到代码的最后一行)。如果代码是更大方法的一部分,那么范围界定将是一个好处。
因此,使用 with_it 的另一个选择是将代码放在单独的方法中。例如:
不知道在这里结束什么,但我想我会投票支持 with_it 包含在标准库中
I sometimes wish for a similar function in the standard library. The name could for example be
with
orwith_it
(Repeating previous code with new name)
Example usage:
As opposed to:
While the latter is easier to understand, the former has the benefit of keeping the variables
list
andhead
scoped and the assignment tox
is more clear in my opinion (the assignment tox
has to be inserted into the last line of the code). Scoping would be a benfit if the code was a part of a larger method.Another option to using
with_it
would thus be putting the code in a separate method. Eg:Not sure what to conclude with here, but I guess I'd vote for with_it to be included in the standard library