문제

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