[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Re: scrambler one-liner

Weirich, James

9/16/2003 2:51:00 PM

> -pe
'gsub!(/\w+/){|w|r=1..w.size-1;w[r]=w[r].split(//).sort_by{rand}.to_s;w}'

Hmmm ... This seems to smbrcale all the lertets but the fsrit. It souhld
lvaee the last ctaeachrr in pclae.

Try:

ruby -pe
'gsub!(/\w+/){|w|(w.size>1)?(r=1...w.size-1;w[r]=w[r].split(//).sort_by{rand
}.to_s;w):w}'

It's leongr, but it gevis the rihgt asnwer.

--
-- Jim Weirich / Compuware
-- FWP Capture Services
-- Phone: 859-386-8855

3 Answers

Xavier Noria

9/16/2003 3:01:00 PM

0

On Tuesday 16 September 2003 16:50, Weirich, James wrote:

> > -pe
>
> ''gsub!(/\w+/){|w|r=1..w.size-1;w[r]=w[r].split(//).sort_by{rand}.to_s
>;w}''
>
> Hmmm ... This seems to smbrcale all the lertets but the fsrit. It
> souhld lvaee the last ctaeachrr in pclae.
>
> Try:
>
> ruby -pe
> ''gsub!(/\w+/){|w|(w.size>1)?(r=1...w.size-1;w[r]=w[r].split(//).sort_
>by{rand }.to_s;w):w}''
>
> It''s leongr, but it gevis the rihgt asnwer.

Oh yes, I got size-1 wrong:

-pe ''gsub!(/\w+/){|w|r=1..w.size-2;w[r]=w[r].split(//).sort_by{rand}.to_s;w}''

It seems there is no need to treat the case w.size > 1 specially because the
slice gives an empty string for sizes == 1 or 2 and everything seems to work
right AFAICT.

-- fxn


sabbyxtabby

9/17/2003 12:05:00 AM

0

Xavier Noria <fxn@hashref.com> wrote:

> -pe ''gsub!(/\w+/){|w|r=1..w.size-2;w[r]=w[r].split(//).sort_by{rand}.to_s;w}''

-pe ''gsub!(/\B\w+\B/){|w|w.split(//).sort_by{rand}}''

In Perl, the criosomapn fnutcoin uesd by srot() is rreqeuid to behave
cisnotsltney, so tihs seohtrr one-lenir may not be ksoher:

-pe ''s!\B\w+\B!join"",sort{.5>rand}$&=~/./g!ge''

Mark J. Reed

9/17/2003 12:13:00 AM

0

On Tue, Sep 16, 2003 at 05:04:48PM -0700, Sabby and Tabby wrote:
> Xavier Noria <fxn@hashref.com> wrote:
>
> > -pe ''gsub!(/\w+/){|w|r=1..w.size-2;w[r]=w[r].split(//).sort_by{rand}.to_s;w}''
>
> -pe ''gsub!(/\B\w+\B/){|w|w.split(//).sort_by{rand}}''
>
> In Perl, the criosomapn fnutcoin uesd by srot() is rreqeuid to behave
> cisnotsltney, so tihs seohtrr one-lenir may not be ksoher:
>
> -pe ''s!\B\w+\B!join"",sort{.5>rand}$&=~/./g!ge''

Right. That''s also true of the block passed to Ruby''s Array#sort
method. The one-liner users Array#sort_by, whose block is used to
assign a key to each array element. It''s basically a shortcut for
a Schwartzian transform:

x = y.sort_by { |i| z(i) }

is roughly equivalent to this Perl code:

$x = map { $_->[1] }
sort { $a->[0] <=> $b->[0] }
map { [z($_), $_] }
@y

-Mark