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
&g开发者_如何转开发t;> 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
shuffle does not accept (and need) arguments. Use:
s.split(//).shuffle.to_s
try this
s.split('').shuffle.join
This will do:
s.chars.shuffle.join
Example:
s = "Hello, World!"
puts s.chars.shuffle.join
Output:
olH!l rWdel,o
精彩评论