Random case chars?

Does anyone have any good ways of transferring a string to random chars?
For example, our string is hello, and i want HeLlO or something… Is
there an easy way of doing this without splitting the string and reading
each value of an array?

thanks

Alle mercoledì 15 agosto 2007, Haze N. ha scritto:

Does anyone have any good ways of transferring a string to random chars?
For example, our string is hello, and i want HeLlO or something… Is
there an easy way of doing this without splitting the string and reading
each value of an array?

thanks

You can try this:

def rand_case str
res = ‘’
str.size.times do |i|
res << str[i].chr.send(rand >= 0.5 ? :upcase : :downcase)
end
res
end

This creates a new string. If you want to modify the original string,
you can
use this

def rand_case! str
str.size.times do |i|
str[i] str[i].chr.send(rand >= 0.5 ? :upcase : :downcase)
end
str
end

I hope this helps

Stefano

On Aug 15, 2007, at 11:36 AM, Haze N. wrote:

Does anyone have any good ways of transferring a string to random
chars?
For example, our string is hello, and i want HeLlO or something… Is
there an easy way of doing this without splitting the string and
reading
each value of an array?

A solution based on gsub:

“foobar”.gsub(/./) do |c|
c.send([:downcase, :upcase][rand(2)])
end

In this case it does not matter the dot does not match newlines, we
will ignore them, if any, and go on with the rest of the string.

– fxn

Sweet that helped a lot, thank you all

Hi,

Am Mittwoch, 15. Aug 2007, 18:36:32 +0900 schrieb Haze N.:

Does anyone have any good ways of transferring a string to random chars?
For example, our string is hello, and i want HeLlO or something… Is
there an easy way of doing this without splitting the string and reading
each value of an array?

“–hello–”.gsub /[a-z]/i do |x| rand(2)>0 ? x.downcase : x.upcase end

class String
def rand_case!
gsub! /[a-z]/i do |x| rand(2)>0 ? x.downcase : x.upcase end
end
end

I don’t know how to treat umlauts or UTF-8.

Bertram

From: Xavier N. [mailto:[email protected]]

“foobar”.gsub(/./) do |c|

c.send([:downcase, :upcase][rand(2)])

end

cool. also,
irb(main):125:0> “hello”.gsub(/./){|c| rand(2)>0 ? c : c.swapcase }
=> “helLo”
or your style,
irb(main):127:0> “hello”.gsub(/./){|c| [c,c.swapcase][rand(2)] }
=> “helLO”

lot of c’s though, wish i could remove them :slight_smile:
kind regards -botp