Josh Morrison
Josh Morrison

Reputation: 7634

New to Ruby - how do I shuffle a string?

Want to shuffle a string. This is my code: what is wrong about it? Thanks.

>> def string_shuffle(s)
>>   s.split('').shuffle(s.length()).join
>>   return s
>> end

Upvotes: 19

Views: 12212

Answers (6)

Hugo
Hugo

Reputation: 2601

This is faster. 'hello'.chars.shuffle.join

Test yourself:

require 'benchmark'

str = 'Hello' * 100
Benchmark.bm(10) do |x|
  x.report('chars')       { str.chars.shuffle.join }
  x.report('split')       { str.split('').shuffle.join }
  x.report('split regex') { str.split(//).shuffle.join }
end
                 user     system      total        real
chars        0.000034   0.000001   0.000035 (  0.000031)
split        0.000029   0.000000   0.000029 (  0.000029)
split regex  0.000192   0.000002   0.000194 (  0.000195)

Upvotes: 8

kwyntes
kwyntes

Reputation: 1302

This will do:

s.chars.shuffle.join

Example:

s = "Hello, World!"
puts s.chars.shuffle.join

Output:

olH!l rWdel,o

Upvotes: 2

Dnyan Waychal
Dnyan Waychal

Reputation: 1418

try this

s.split('').shuffle.join

Upvotes: 1

Serabe
Serabe

Reputation: 3924

return s is both not needed and wrong. Not needed because Ruby returns whatever is executed last and wrong because you are not changing s, you are creating a new string.

Furthermore, you can just add the shuffle method directly to String if you find it useful, but beware of monkeypatching too much.

class String

  def shuffle
    self.split('').shuffle.join
  end
end

Upvotes: 8

kyrylo
kyrylo

Reputation: 1748

If understand you correctly, you want this:

def string_shuffle(s)
  s.split("").shuffle.join
end

string_shuffle("The Ruby language")
=> "ea gu bgTayehRlnu"

Upvotes: 24

Emiliano Poggi
Emiliano Poggi

Reputation: 24826

shuffle does not accept (and need) arguments. Use:

 s.split(//).shuffle.to_s

Upvotes: 2

Related Questions