从嵌套数组中提取数组的任何想法?
这
[["Total", "$ 3"], ["Subtotal", "$ 2"], ["Paid", "$ 1"]]
要
[["Total", "$ 3"], ["Subtotal", "$2"]]
此外,我想要检索元素
["Paid", "$ 1"]
我喜欢用这个名字提取。
Total
,Subtotal
或Paid
答案 0 :(得分:1)
从你的问题来看,目前尚不清楚你想要解决的问题。
如果数组中有其他“键”并且只想要基于子数组中第一项的某些特定项,则应查看assoc方法:
array = [["Total", "$ 3"], ["Subtotal", "$ 2"], ["Paid", "$ 1"]]
p array.assoc("Paid") #=> ["Paid", "$ 1"]
p ["Total","Subtotal"].map{|key| array.assoc key} #=> [["Total", "$ 3"], ["Subtotal", "$ 2"]]
如果你想改变原始数组,我认为分两步完成它是最简单的解决方案:
item_index = array.find_index{|x| x.first == "Paid"}
paid = array.delete_at(item_index)
p paid #=> ["Paid", "$ 1"]
p array #=> [["Total", "$ 3"], ["Subtotal", "$ 2"]]
答案 1 :(得分:0)
答案 2 :(得分:0)
请查看以下控制台o / p
[11] pry(main)> arr = [["Total", "$ 3"], ["Subtotal", "$ 2"], ["Paid", "$ 1"]]
=> [["Total", "$ 3"], ["Subtotal", "$ 2"], ["Paid", "$ 1"]]
[12] pry(main)> arr[0..1]
=> [["Total", "$ 3"], ["Subtotal", "$ 2"]]
[13] pry(main)> arr[2]
=> ["Paid", "$ 1"]
正如你想要的名字'总'
[17] pry(main)> arr = [["Total", "$ 3"], ["Subtotal", "$ 2"], ["Paid", "$ 1"]]
=> [["Total", "$ 3"], ["Subtotal", "$ 2"], ["Paid", "$ 1"]]
[18] pry(main)> arr.select{|ar| ar[0].downcase.include?('total')}
=> [["Total", "$ 3"], ["Subtotal", "$ 2"]]
[19] pry(main)> arr.reject{|ar| ar[0].downcase.include?('total')}.first
=> ["Paid", "$ 1"]
[20] pry(main)>
答案 3 :(得分:0)
尝试以下:
original_array = [["Total", "$ 3"], ["Subtotal", "$ 2"], ["Paid", "$ 1"]]
extract_array = original_array.values_at(-1).flatten
输出:["Paid", "$ 1"]
remain_array = original_array - extract_array
输出:[["Total", "$ 3"], ["Subtotal", "$ 2"]]
答案 4 :(得分:0)
如果我正确理解了这个问题:
input = [
["Total", "$ 3"],
["Subtotal", "$ 2"],
["Paid", "$ 1"]
]
input.to_h
#⇒ {
# "Paid" => "$ 1",
# "Subtotal" => "$ 2",
# "Total" => "$ 3"
# }
input.to_h['Total']
#⇒ "$ 3"
my, rest = input.partition { |k, _| k == 'Total' }
my
#⇒ [["Total", "$ 3"]]
答案 5 :(得分:0)
最简单的方法是:
*totals, paid = [["Total", "$ 3"], ["Subtotal", "$ 2"], ["Paid", "$ 1"]]
totals # [["Total", "$ 3"], ["Subtotal", "$ 2"]]
paid # ["Paid", "$ 1"]