从嵌套的数组中提取数组

时间:2016-12-26 06:16:28

标签: ruby

从嵌套数组中提取数组的任何想法?

[["Total", "$ 3"], ["Subtotal", "$ 2"], ["Paid", "$ 1"]]

  [["Total", "$ 3"], ["Subtotal", "$2"]] 

此外,我想要检索元素

["Paid", "$ 1"]

更新

我喜欢用这个名字提取。 TotalSubtotalPaid

6 个答案:

答案 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)

您需要Array#pop

x = [1,2,3]  #=> [1, 2, 3]
x.pop        #=> 3
x            #=> [1, 2]

而不是原子值,你将拥有你的子阵列。

答案 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"]