1

我有几个数组,我只会说四个。例如:

LOCATION  = [:new_york, :california, :alaska, :missouri, :mississippi, :florida]
TYPE      = [:high_rise, :mid_rise, :low_rise, :loft, :townhouse, :hotel]
OWNERSHIP = [:coop, :condo, :condop, :rental, :single_family, :multi_family]
BLDG_AGE  = [:historic, :pre-war, :post-war, :modern]

我需要一个脚本来生成这些的每一种组合。这里有些例子:

:new_york
:new_york, :high_rise
:new_york, :high_rise, :coop
:new_york, :high_rise, :coop, :historic

这些是简单的,只是一堆嵌套循环。我还需要其他组合。例如:

:new_york, :coop
:new_york, :pre-war
:new_york, :rental, :modern
:new_york, :high_rise, :single_family

但只要想想每个组合,除了只有成员LOCATION可以单独出现的例外。

4

1 回答 1

3

假设您想要:pre_war,:post_war而不是:pre-war, :post-war

LOCATION  = [:new_york, :california, :alaska, :missouri, :mississippi, :florida]
TYPE      = [:high_rise, :mid_rise, :low_rise, :loft, :townhouse, :hotel]
OWNERSHIP = [:coop, :condo, :condop, :rental, :single_family, :multi_family]
BLDG_AGE  = [:historic, :pre_war, :post_war, :modern]

LOCATION.product([nil] + TYPE, [nil] + OWNERSHIP, [nil] + BLDG_AGE)
.map(&:compact)

或更简洁:

LOCATION.product(*[TYPE, OWNERSHIP, BLDG_AGE].map{|a| [nil] + a})
.map(&:compact)
于 2013-05-31T01:24:24.313 回答