开发者

New to Ruby - how do I shuffle a string?

开发者 https://www.devze.com 2023-03-27 14:46 出处:网络
Want to shuffle a string. This is my code: what is wrong about it? Thanks. >> def string_shuffle(s)

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
0

精彩评论

暂无评论...
验证码 换一张
取 消