1

Is there a built in function or convention for when you want to do combinations of states concisely?

Given the following:

{
  animal: [:dog, :cat],
  disposition: [:grumpy, :hungry, :sleepy]
}

I want to make:

[
  {animal: :dog, disposition: :grumpy},
  {animal: :dog, disposition: :hungry},
  {animal: :dog, disposition: :sleepy},
  {animal: :cat, disposition: :grumpy},
  {animal: :cat, disposition: :hungry},
  {animal: :cat, disposition: :sleepy}
]

taking any number of input states, i.e. more than 2.

Others must have solved this before me in an elegant fashion?

Python has an array way of doing it here

Community
  • 1
  • 1
xxjjnn
  • 14,591
  • 19
  • 61
  • 94

2 Answers2

2

intial hash:

a={  
  animal: [:dog, :cat],  
  disposition: [:grumpy, :hungry, :sleepy]  
}  
b= a[:animal].product(a[:disposition]).collect do |c|
  {animal: c[0], disposition: c[1]}
end
rejin
  • 179
  • 1
  • 13
1

This SO answer should work.

[{:animal=>:dog, :disposition=>:grumpy}, {:animal=>:dog, :disposition=>:hungry}, {:animal=>:dog, :disposition=>:sleepy}, {:animal=>:cat, :disposition=>:grumpy}, {:animal=>:cat, :disposition=>:hungry}, {:animal=>:cat, :disposition=>:sleepy}]

Community
  • 1
  • 1
Ju Liu
  • 3,939
  • 13
  • 18
  • combinations = input.values[0].product(*input.values[1..-1]).map{|p| Hash[input.keys.zip p]} – xxjjnn Jan 14 '14 at 10:53