通过合并数组创建嵌套数组(2D)[重复]
Posted
技术标签:
【中文标题】通过合并数组创建嵌套数组(2D)[重复]【英文标题】:Create nested arrays (2D) by merging arrays [duplicate] 【发布时间】:2013-01-19 13:52:43 【问题描述】:可能重复: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
并将每套西装输入Face
13 次,以创建一个类似于[["Two", "Spades"],["Three", "Spades"]... ["Ace", "Diamonds"]]
的二维数组
【问题讨论】:
【参考方案1】:正如 Sunny 所链接的问题中所发布的,您正在寻找 product
:
Faces.product Suits
【讨论】:
【参考方案2】:通常,变量应采用snake_case
的形式,常量应采用SCREAMING_SNAKE_CASE
的形式。很难说你是想创建常量还是变量。
您还可以使用%welements here
以更简单的方式实例化您的数组。
浏览documentation 以了解这里发生了什么。
faces = %wTwo 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 = %wSpades 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 >=。
【讨论】:
以上是关于通过合并数组创建嵌套数组(2D)[重复]的主要内容,如果未能解决你的问题,请参考以下文章