Ruby 数组:select()、collect() 和 map()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9915552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby Arrays: select(), collect(), and map()
提问by ingalcala
The syntax for mapping:
映射语法:
a = ["a", "b", "c", "d"] #=> ["a", "b", "c", "d"]
a.map {|item|"a" == item} #=> [true, false, false, false]
a.select {|item|"a" == item} #=> ["a"]
Question how about if I have:
问题如果我有:
irb(main):105:0> details[1]
=> {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", :qty=>"",
:qty2=>"1", :price=>"5,204.34 P"}
I want to delete every entry which has an empty qty value on this array or select only the ones with some value in it.
我想删除在这个数组上有空数量值的每个条目,或者只选择其中有一些值的条目。
I tried:
我试过:
details.map {|item|"" == item}
Just returns a lot of false and then when I use the same just change map to select I get:
只是返回很多错误,然后当我使用相同的只是更改地图来选择我得到:
[]
回答by Emily
It looks like detailsis an array of hashes. So iteminside of your block will be the whole hash. Therefore, to check the :qtykey, you'd do something like the following:
它看起来像是details一个哈希数组。所以item你的块内部将是整个哈希。因此,要检查:qty密钥,您需要执行以下操作:
details.select{ |item| item[:qty] != "" }
That will give you all items where the :qtykey isn't an empty string.
这将为您提供:qty键不是空字符串的所有项目。
回答by Niklas B.
EDIT:I just realized you want to filter details, which is an array of hashes. In that case you could do
编辑:我刚刚意识到你想要过滤details,它是一个散列数组。在这种情况下,你可以做
details.reject { |item| item[:qty].empty? }
The inner data structure itself is not an Array, but a Hash. You can also use selecthere, but the block is given the key and value in this case:
内部数据结构本身不是数组,而是哈希。你也可以select在这里使用,但在这种情况下,块被赋予了键和值:
irb(main):001:0> h = {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", :qty=>"", :qty2=>"1", :price=>"5,204.34 P"}
irb(main):002:0> h.select { |key, value| !value.empty? }
=> {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .",
:qty2=>"1", :price=>"5,204.34 P"}
Or using reject, which is the inverse of select(excludes all items for which the given condition holds):
或者使用reject,它是select(排除满足给定条件的所有项目)的倒数:
h.reject { |key, value| value.empty? }
Note that this is Ruby 1.9. If you have to maintain compatibility with 1.8, you could do:
请注意,这是 Ruby 1.9。如果您必须保持与 1.8 的兼容性,您可以这样做:
Hash[h.reject { |key, value| value.empty? }]
回答by Michael Berkowski
When dealing with a hash {}, use both the key and value to the block inside the ||.
处理散列时{},将键和值同时用于||.
details.map {|key,item|"" == item}
=>[false, false, true, false, false]

