如何拒绝具有特定条件的数组块

时间:2015-08-18 06:48:51

标签: ruby-on-rails arrays ruby wsdl

这是阵列。我需要拒绝具有item_id == 200的数组块。

:invoice_lines=>[{:amount=>"60.00", :description=>"repair   call",:id=>"10138500", :item_id=>"80062",  :price=>"60.0000000000"}, 
{:amount=>"9.83", :description=>"Tax", :id=>"10138501", :item_id=>"200", :price=>"8.1875000000"}, 
{:amount=>"60.00",  :description=>"Wireless Router", :id=>"10138502", :item_id=>"80060", :price=>"60.0000000000"}]

我正在尝试这种方式,但无法得到结果。

  i = 0
  num = invoice[:invoice_lines].length
  items = []
  while i < num
    if invoice[:invoice_lines][i][item_id] == 200
       invoice[:invoice_lines].delate_at(i)
    end
    i += 1
  end

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

试试这个

array = []

invoice[:invoice_lines].each do |line|
  array << line unless line[:item_id] == "200"
end unless invoice[:invoice_lines].blank?

array

array将返回item_id不等于200的所有发票行

正如 ndn 的评论中所述,如果您要从rejecthttp://ruby-doc.org/core-2.2.0/Array.html#method-i-reject-21

中删除哈希值,可以使用invoice[:invoice_lines]

希望有所帮助!