Random case chars?

H

Haze Noc

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
 
S

Stefano Crocco

Alle mercoled=C3=AC 15 agosto 2007, Haze Noc 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 =3D ''
str.size.times do |i|
res << str.chr.send(rand >=3D 0.5 ? :upcase : :downcase)
end
res
end

This creates a new string. If you want to modify the original string, you c=
an=20
use this

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

I hope this helps

Stefano
 
X

Xavier Noria

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
 
B

Bertram Scharpf

Hi,

Am Mittwoch, 15. Aug 2007, 18:36:32 +0900 schrieb Haze Noc:
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
 
P

Peña, Botp

From: Xavier Noria [mailto:[email protected]]=20
# "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 }
=3D> "helLo"
or your style,
irb(main):127:0> "hello".gsub(/./){|c| [c,c.swapcase][rand(2)] }
=3D> "helLO"

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,266
Messages
2,571,318
Members
48,002
Latest member
EttaPfeffe

Latest Threads

Top