ruby on rails - Generate array of all combinations of an existing array -
if have array in ruby, this:
["foo", "bar", "bat"] how can generate new array every combination of values?
i need output this:
["foo", "bar", "bat", "foo-bar", "foo-bat", "bar-bat", "foo-bar-bat"] order unimportant. also, not need both "foo-bar" , "bar-foo".
the original array may have 5-6 members.
ar = ["foo", "bar", "bat"] p 1.upto(ar.size).flat_map {|n| ar.combination(n).map{|el| el.join('-')}} #=>["foo", "bar", "bat", "foo-bar", "foo-bat", "bar-bat", "foo-bar-bat"]
Comments
Post a Comment