将方法应用于数组/可枚举中的每个元素
这是我的数组:
array = [:one,:two,:three]
我想对所有数组元素应用 to_s
方法来获取 array = ['one','two','third']
。
我该如何做到这一点(将可枚举的每个元素转换为其他元素)?
This is my array:
array = [:one,:two,:three]
I want to apply to_s
method to all of my array elements to get array = ['one','two','three']
.
How can I do this (converting each element of the enumerable to something else)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这会起作用:
This will work:
您可以使用
map
或 < a href="http://www.ruby-doc.org/core/classes/Array.html#M000250" rel="noreferrer">map!
分别,第一个将返回一个新列表,第二个将就地修改列表:You can use
map
ormap!
respectively, the first will return a new list, the second will modify the list in-place:值得注意的是,如果您有一个对象数组,想要将其单独传递到具有不同调用者的方法中,如下所示:
您可以使用
method
方法与块扩展行为相结合来简化:如果您不熟悉,
method
的作用是将与传递给它的符号关联的方法封装在 Proc 中并返回它。 & 符号将此 Proc 扩展为一个块,该块很好地传递给map
。map
的返回是一个数组,我们可能希望将其格式化得更好一点,因此需要join
。需要注意的是,与
Symbol#to_proc
一样,您无法将参数传递给辅助方法。It's worth noting that if you have an array of objects you want to pass individually into a method with a different caller, like this:
You can use the
method
method combined with block expansion behavior to simplify:If you're not familiar, what
method
does is encapsulates the method associated with the symbol passed to it in a Proc and returns it. The ampersand expands this Proc into a block, which gets passed tomap
quite nicely. The return ofmap
is an array, and we probably want to format it a little more nicely, hence thejoin
.The caveat is that, like with
Symbol#to_proc
, you cannot pass arguments to the helper method.array.map!(&:to_s)
将原始数组修改为['one','two','third']
array.map(& ;:to_s)
返回数组['one','two','third']
。array.map!(&:to_s)
modifies the original array to['one','two','three']
array.map(&:to_s)
returns the array['one','two','three']
.