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
If understand you correctly, you want this:
def string_shuffle(s)
s.split("").shuffle.join
end
string_shuffle("The Ruby language")
=> "ea gu bgTayehRlnu"
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With