Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New to Ruby - how do I shuffle a string?

Tags:

ruby

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
like image 976
Josh Morrison Avatar asked Aug 10 '11 07:08

Josh Morrison


3 Answers

If understand you correctly, you want this:

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

string_shuffle("The Ruby language")
=> "ea gu bgTayehRlnu"
like image 111
kyrylo Avatar answered Oct 12 '22 00:10

kyrylo


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
like image 28
Serabe Avatar answered Oct 11 '22 22:10

Serabe


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
like image 21
Hugo Avatar answered Oct 11 '22 23:10

Hugo