["a", "b", "c", "d"] a.map {|item|"a" == item} #=> [true-6ren">
gpt4 book ai didi

Ruby 数组 : select(), collect() 和 map()

转载 作者:数据小太阳 更新时间:2023-10-29 06:18:09 25 4
gpt4 key购买 nike

映射语法:

a = ["a", "b", "c", "d"]      #=> ["a", "b", "c", "d"] 
a.map {|item|"a" == item} #=> [true, false, false, false]
a.select {|item|"a" == item} #=> ["a"]

问如果我有:

 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"}

我想删除这个数组中每一个数量为空的条目,或者只选择其中有一些值的条目。

我试过:

details.map {|item|"" == item}

只是返回很多错误,然后当我使用相同的只是更改 map 来选择时,我得到:

[]

最佳答案

看起来 details 是一个哈希数组。因此, block 内的 item 将是整个哈希。因此,要检查 :qty 键,您需要执行如下操作:

details.select{ |item| item[:qty] != "" }

这将为您提供 :qty 键不是空字符串的所有项目。

official select documentation

关于Ruby 数组 : select(), collect() 和 map(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9915552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com