我有几个阵列,我只会说四个。例如:
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
的成员才能单独出现。
答案 0 :(得分: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)