就地枚举
我正在使用 ruby 1.8.7 和 ruby on Rails 3.x 。我有很多这样的行,
lines = lines.map {|e| e.strip}
lines = lines.map {|e| e.upcase}
lines = lines.map {|e| sanitize_element(e)}
而不是每次都为行分配新值,有更好的方法来处理这个问题。我知道我可以
lines = lines.map {|e| sanitize_element(e.strip.upcase) }
,但这不是这个问题的重点。主要是寻找是否有一种方法可以处理上述情况,而无需每次都为行赋值。
基本上我正在寻找像这样优雅的解决方案,但我知道 Enumerable 中没有 map!
。
lines.map! {|e| e.strip}
只是确保我不会错过红宝石功能。
I am using ruby 1.8.7 and ruby on rails 3.x . I have many lines like this
lines = lines.map {|e| e.strip}
lines = lines.map {|e| e.upcase}
lines = lines.map {|e| sanitize_element(e)}
Rather than assigning new values to lines every time is there a better way to handle this. I know I can do
lines = lines.map {|e| sanitize_element(e.strip.upcase) }
but that is not the main point of this question. The main thing is to find if there is a way to handle the above case without assigning value to lines every time.
Basically I am looking for a solution as elegant as this, but I know there isn't a map!
in Enumerable.
lines.map! {|e| e.strip}
Just making sure that I am not missing out on a ruby feature.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,通过使用
Array#map!
:通常,像
map
这样的不可变方法会与像map!
这样的危险方法配对,这会导致接收器要修改。我建议不要使用它们,因为良好的函数式可枚举编程的一半目的是获得不变性的好处(引用透明度等)。但如果您要对每个枚举重新分配,您不妨使用map!
。Yes, by using
Array#map!
:Often, an immutable method like
map
is paired with a dangerous one likemap!
, which causes the receiver to be modified. I recommend against using these, since half the point of nice, functional-style enumerable programming is to get the benefits of immutability (referential transparency, etc.). But if you're going to reassign on each enumeration, you might as well usemap!
.如果我正确理解你的问题,你可以写
得很流利。这是你的意思吗?
If I understand your question correctly, you could write
in a fluent fashion. Is this what you meant?
如果
sanitize_element!
存在,你可以尝试这种方式:我认为它看起来更清晰。
In case if
sanitize_element!
exists you can try this way:I think it looks more clear.
出于兴趣,请注意,您可以保留数组并专注于修改字符串本身。像这样:
在随机数据的快速基准测试中,它的运行时间大约是多
map!
版本的 2/3,尽管显然您希望在实际数据上验证这一点和操作。For interest, note that you could leave the array alone and concentrate on modifying the strings themselves. Like this:
In a quick benchmark on random data this looked like it ran in about 2/3rds the time of the multiple-
map!
version, although obviously you'd want to verify this on your actual data and operations.