ruby on rails - Dynamically get all combinations of all elements of arrays -


important: can choose 1 element each array.

i'm writing code let me test quiz permutations. below current hardcoded way return array of possible permutations. need adapt dynamic, there more arrays added later.

i thinking of method accept array of options, , return array of permutations, brain breaks after first loop. appreciated.

options = [   [["geek", "chef", "supporter", "fashionista"]],   [["0-1000", "1001-10000", "no limit"]],   [["many", "for one"]] ]   def test_gifts(options)   options.each_with_index |a,index|    ....   end end 

hardcoded way:

character_types = ["geek","chef", "supporter", "fashionista"] price_ranges    = ["0-1,000","1,001-10000","no limit"] party_size      = ["many", "for one"]   permutations = [] character_types.each |type|   price_ranges.each |price|     party_size.each |party|       permutations << [type, price, party]     end       end end 

which returns

[["geek", "0-1,000", "many"], ["geek", "0-1,000", "for one"], ["geek", "1,001-10000", "many"], ["geek", "1,001-10000", "for one"], ["geek", "no limit", "many"], ["geek", "no limit", "for one"], ["chef", "0-1,000", "many"], ["chef", "0-1,000", "for one"], ["chef", "1,001-10000", "many"], ["chef", "1,001-10000", "for one"], ["chef", "no limit", "many"], ["chef", "no limit", "for one"], ["supporter", "0-1,000", "many"], ["supporter", "0-1,000", "for one"], ["supporter", "1,001-10000", "many"], ["supporter", "1,001-10000", "for one"], ["supporter", "no limit", "many"], ["supporter", "no limit", "for one"], ["fashionista", "0-1,000", "many"], ["fashionista", "0-1,000", "for one"], ["fashionista", "1,001-10000", "many"], ["fashionista", "1,001-10000", "for one"], ["fashionista", "no limit", "many"], ["fashionista", "no limit", "for one"]]  

use array#product method this:

character_types.product(price_ranges, party_size) 

to handle unknown number of other arrays:

arrays_to_permute = [character_types, price_ranges, party_size] first_array, *rest_of_arrays = arrays_to_permute first_array.product(*rest_of_arrays) 

Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -