Home > Enterprise >  How to get every possible combination of string from array/hash in ruby?
How to get every possible combination of string from array/hash in ruby?

Time:01-29

I'm junior backend trying ruby. I have these data:

people = ["Andy", "Budi", "Charles"]
vehicles = ["Bicycle", "Car", "Bajaj"]
destinations = ["USA", "Bali", "Paradise"]


string_format = %{person} ride %{vehicle} to %{destination}

How to get the all possible combination of the string using ruby? Expected output total of 27 items (3 x 3 x 3):

1. Andy ride Bicycle to USA
2. Andy ride Bicycle to Bali
3. Andy ride Bicycle to Paradise
4. Andy ride Car to USA

...

27. Charles ride Bajaj to Paradise

the code should be extensible, because later we will add more array such as:

adjectives = ["happily", "sadly"]

string_format = %{destination} has been visited by %{person} using %{his_or_her} %{vehicle} %{adjectives}

CodePudding user response:

You can use Array#product to return an array with all combinations:

people.product(vehicles, destinations)
# => [["Andy", "Bicycle", "USA"], ["Andy", "Bicycle", "Bali"], ["Andy", "Bicycle", "Paradise"], ["Andy", "Car", "USA"], ["Andy", "Car", "Bali"], ["Andy", "Car", "Paradise"], ["Andy", "Bajaj", "USA"], ["Andy", "Bajaj", "Bali"], ["Andy", "Bajaj", "Paradise"], ["Budi", "Bicycle", "USA"], ["Budi", "Bicycle", "Bali"], ["Budi", "Bicycle", "Paradise"], ["Budi", "Car", "USA"], ["Budi", "Car", "Bali"], ["Budi", "Car", "Paradise"],["Budi", "Bajaj", "USA"],["Budi", "Bajaj", "Bali"],["Budi", "Bajaj", "Paradise"],["Charles", "Bicycle", "USA"],["Charles", "Bicycle", "Bali"],["Charles", "Bicycle", "Paradise"],["Charles", "Car", "USA"],["Charles", "Car", "Bali"],["Charles", "Car", "Paradise"],["Charles", "Bajaj", "USA"],["Charles", "Bajaj", "Bali"],["Charles", "Bajaj", "Paradise"]]

Which can be used to output your list like this:

people.product(vehicles, destinations).each do |person, vehicle, destination|
  puts "#{person} ride #{vehicle} to #{destination}"
end
  • Related