通过合并数组创建嵌套数组(2D)

时间:2013-02-04 19:22:48

标签: ruby arrays nested

  

可能重复:
  Combination of two arrays in Ruby

Faces = "Two Three Four Five Six Seven Eight Nine Ten Jack Queen King Ace"
Suits = "Spades Clubs Hearts Diamonds"
Face = []
Face = Faces.split * 4
Suits.split

我正在寻找suits.split array并将每件套装13次送入Face以创建一个类似于[["Two", "Spades"],["Three", "Spades"]... ["Ace", "Diamonds"]]

的2D数组

2 个答案:

答案 0 :(得分:3)

正如Sunny发布的问题中所述,您正在寻找product

Faces.product Suits

答案 1 :(得分:1)

通常,变量应采用snake_case的形式和SCREAMING_SNAKE_CASE中的常量。如果你试图创建常量或变量,很难说。

您还可以使用%w{elements here}以更简单的方式实例化数组。

略过documentation以了解这里发生了什么。

faces = %w{Two Three Four Five Six Seven Eight Nine Ten Jack Queen King Ace}
 => ["Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace"] 
suites = %w{Spades Clubs Hearts Diamonds}
 => ["Spades", "Clubs", "Hearts", "Diamonds"] 
 faces.product(suites)
 => [["Two", "Spades"], ["Two", "Clubs"], ["Two", "Hearts"], ["Two", "Diamonds"], ["Three", "Spades"], ["Three", "Clubs"], ["Three", "Hearts"], ["Three", "Diamonds"], ["Four", "Spades"], ["Four", "Clubs"], ["Four", "Hearts"], ["Four", "Diamonds"], ["Five", "Spades"], ["Five", "Clubs"], ["Five", "Hearts"], ["Five", "Diamonds"], ["Six", "Spades"], ["Six", "Clubs"], ["Six", "Hearts"], ["Six", "Diamonds"], ["Seven", "Spades"], ["Seven", "Clubs"], ["Seven", "Hearts"], ["Seven", "Diamonds"], ["Eight", "Spades"], ["Eight", "Clubs"], ["Eight", "Hearts"], ["Eight", "Diamonds"], ["Nine", "Spades"], ["Nine", "Clubs"], ["Nine", "Hearts"], ["Nine", "Diamonds"], ["Ten", "Spades"], ["Ten", "Clubs"], ["Ten", "Hearts"], ["Ten", "Diamonds"], ["Jack", "Spades"], ["Jack", "Clubs"], ["Jack", "Hearts"], ["Jack", "Diamonds"], ["Queen", "Spades"], ["Queen", "Clubs"], ["Queen", "Hearts"], ["Queen", "Diamonds"], ["King", "Spades"], ["King", "Clubs"], ["King", "Hearts"], ["King", "Diamonds"], ["Ace", "Spades"], ["Ace", "Clubs"], ["Ace", "Hearts"], ["Ace", "Diamonds"]] 

请记住,产品仅适用于Ruby 1.9> =。