777Newb 777Newb - 1 month ago 4
Ruby Question

Combining random elements of multiple arrays

In Ruby, how would I select a random element from one array and combine it with a randomly selected element from a second array?

For example if I have the arrays:

array1 = ["x", "y", "z"]
array2 = ["a", "b", "c"]

I'm looking for the output to be (array1_element)(array2_element)(array1_element) like xby or ycz or xbx so on and so forth. Can Ruby's .sample method be used on multiple arrays to print out a single string?


There are a few ways to do this.

1) You can use sample method.

array1.sample #=> return a random element from the array.

Then you can use string interpolation like

result = "#{array1.sample}#{array2.sample}#{array3.sample}" #=> ie "xby"

2) You can generate random index values


This will generate a random index from 0 to length-1 and call the [] method on the array. You can then use string interpolation as well.

3) You can use the shuffle method then first method


shuffle will, well, shuffle the array, and you can just return the first element.

I'm just listing the few I can come up with off the top of my head. There are probably tons of other ways to do this.