[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Random case chars?

Haze Noc

8/15/2007 9:37:00 AM

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
--
Posted via http://www.ruby-....

5 Answers

Stefano Crocco

8/15/2007 9:48:00 AM

0

Alle mercoledì 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 = ''
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

Xavier Noria

8/15/2007 10:03:00 AM

0

On Aug 15, 2007, at 11:36 AM, Haze Noc 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


Bertram Scharpf

8/15/2007 10:11:00 AM

0

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

--
Bertram Scharpf
Stuttgart, Deutschland/Germany
http://www.bertram-...

Haze Noc

8/15/2007 10:24:00 AM

0

Sweet that helped a lot, thank you all
--
Posted via http://www.ruby-....

Peña, Botp

8/16/2007 12:34:00 AM

0

From: Xavier Noria [mailto:fxn@hashref.com]
# "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 :)
kind regards -botp