سؤال

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

هل كانت مفيدة؟

المحلول 2

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}]

نصائح أخرى

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top