shuffle a string in ruby

One way to shuffle a string in Ruby is to convert it to an array of characters, shuffle the array using a randomization algorithm, and then join the shuffled array back into a string. Here's an example:

main.rb
string = "hello world"
shuffled = string.chars.shuffle.join
puts shuffled
74 chars
4 lines

This will output a shuffled version of the original string, like this:

main.rb
dlrow olleh
12 chars
2 lines

Note that this method relies on Ruby's built-in shuffle method, which uses a randomized algorithm to shuffle the elements of an array. If you need more control over the shuffling process, you can also pass a custom random number generator to the shuffle method, like this:

main.rb
string = "hello world"
random = Random.new(1234) # create a new random number generator with seed 1234
shuffled = string.chars.shuffle(random: random).join
puts shuffled
170 chars
5 lines

This will shuffle the characters of the string using the specified random number generator, which will produce the same shuffled result every time the program is run with the same seed value (in this case, 1234).

gistlibby LogSnag