二维数组语法,其中string作为索引

时间:2015-12-23 11:07:19

标签: arrays ruby

我需要下面这样的东西。

products['first_category'][0] = ['aaa', 'bb', 'ccc']
products['first_category'][1] = ['aa', 'bb', 'cc']
products['first_category'][2] = ['a', 'b', 'c']
products['second_category'][0] = ['asd', 'sdfb', 'csdfd']
products['second_category'][1] = ['sdf', 'bsdf', 'dsfssd']
all_products = products['first_category'] + products['second_category']

这应该产生一个

形式的数组
all_products[0] = ['aaa', 'bb', 'ccc']
all_products[1] = ['aa', 'bb', 'cc']
all_products[2] = ['a', 'b', 'c']
all_products[3] = ['asd', 'sdfb', 'csdfd']
all_products[4] = ['sdf', 'bsdf', 'dsfssd']

但我不知道如何在ruby中实现它。我尝试了这个,但它给出了错误。

3 个答案:

答案 0 :(得分:2)

▶ products = {}
#⇒ {}
▶ products['first_category'] = []
#⇒ []
▶ products['second_category'] = []
#⇒ []
▶ products['first_category'][0] = ['aaa', 'bb', 'ccc']
▶ products['first_category'][1] = ['aa', 'bb', 'cc']
▶ products['first_category'][2] = ['a', 'b', 'c']
▶ products['second_category'][0] = ['asd', 'sdfb', 'csdfd']
▶ products['second_category'][1] = ['sdf', 'bsdf', 'dsfssd']
▶ all_products = products['first_category'] + products['second_category']
#⇒ [
#  [0] [
#    [0] "aaa",
#    [1] "bb",
#    [2] "ccc"
#  ],
#  [1] [
#    [0] "aa",
#    [1] "bb",
#    [2] "cc"
#  ],
#  [2] [
#    [0] "a",
#    [1] "b",
#    [2] "c"
#  ],
#  [3] [
#    [0] "asd",
#    [1] "sdfb",
#    [2] "csdfd"
#  ],
#  [4] [
#    [0] "sdf",
#    [1] "bsdf",
#    [2] "dsfssd"
#  ]
# ]

这里的技巧是:

  1. 由于您的顶级索引是字符串,因此对象本身必须是哈希而不是数组。数组可能只有整数索引。
  2. 必须先显式创建所有子数组,然后才能向其添加元素。

答案 1 :(得分:1)

你的代码很好。只需使用以下行创建products(将其添加到您的代码段顶部)

products = Hash.new {|hash, key| hash[key] = [] }

您需要使用Hash,因为Array无法使用非数字索引。 Hash允许您以类似数组的语法接受其元素,即使它是一个字典。此外,上面的代码将确保如果给定键没有条目,则使用空数组作为其值并添加到哈希值。

工作样本:

products = Hash.new {|hash, key| hash[key] = [] }

products['first_category'][0] = ['aaa', 'bb', 'ccc']
products['first_category'][1] = ['aa', 'bb', 'cc']
products['first_category'][2] = ['a', 'b', 'c']

products['second_category'][0] = ['asd', 'sdfb', 'csdfd']
products['second_category'][1] = ['sdf', 'bsdf', 'dsfssd']

all_products = products['first_category'] + products['second_category']

p all_products[0]
#=> ["aaa", "bb", "ccc"]
p all_products[1]
#=> ["aa", "bb", "cc"]
p all_products[2]
#=> ["a", "b", "c"]
p all_products[3]
#=> ["asd", "sdfb", "csdfd"]
p all_products[4]
#=> ["sdf", "bsdf", "dsfssd"]

答案 2 :(得分:0)

试试

all_products = products.values.flatten(1)

将值取为数组,忽略键并将其展平为1