【发布时间】:2014-06-21 19:04:46
【问题描述】:
我有一个哈希数组myhash:
myhash
=> [{"product_id"=>"1", "test"=>"2", "retest"=>"42"}, {"product_id"=>"1", "test"=>"2", "retest"=>"42"}]
我想将哈希值映射到 product_id 的值。我这样做了:
myhash.map{|item| item['product_id']}
# => ["1", "1"]
这给了我想要的。
有没有办法让它更好地使用 map proc?我试过myhash.map(&:fetch('product_id')),但无济于事。
编辑: 换句话说,感谢@7stud 试图回答,我恢复了这种情况:
a.map(&:"fetch('product_id')")
=> NoMethodError: undefined method `fetch('product_id')' for {"product_id"=>"1", "test"=>"2", "retest"=>"42"}:Hash
from (irb):5:in `map'
from (irb):5
from /home/shideneyu/.rbenv/versions/1.9.3-p194/bin/irb:12:in `<main>'
或者,当我这样做时:
{"product_id"=>"1", "test"=>"2", "retest"=>"42"}.fetch('product_id')
=> "1"
它检索良好的价值。那么问题是我在使用地图时无法将参数传递给fetch 方法。该怎么做?
【问题讨论】:
-
没有内置的..创建你自己的proc对象...查看this answer以了解如何构建..
-
还是谢谢你,所以我想我写的第一个可行的解决方案是最简单和更干净的?
-
当然你的也是最快和干净的..
-
无意冒犯,我喜欢尽可能使用 map(&:),@Arup Rakshit,我只是想知道为什么那个 fetch 不起作用。我仍然没有答案。
-
@sawa,对不起,这是我的 irb 测试的剩余部分,我编辑了我的问题。