From: Dave Thomas Date: 2001-10-09T04:58:24+09:00 Subject: [ruby-talk:22259] Re: [Newbie] Switching from Perl : suffling Damien WYART writes: > Dear All, > > Slowly switching from Perl to Ruby, I do not feel very confident with > what I write in Ruby. > > I would like to get a script to shuffle records from STDIN to STDOUT. > The Perl version I use is as follows : > > ,---- > | #!/usr/bin/perl > | > | undef $/; > | $/ = "\n%\n"; > | > | sub shuffle { > | srand; > | my $array = shift; > | for (my $i = @$array; --$i > 0; ) { > | my $j = int rand ($i+1); > | @$array[$i,$j] = @$array[$j,$i]; > | } > | } > | > | while (<>) { > | push (@lines, $_); > | } > | shuffle(\@lines); > | foreach (@lines) { > | print $_; > | } > `---- How about something like class Array def shuffle each_index {|i| o = rand(size); self[i], self[o] = self[o], self[i] } end end original = readlines("\n%\n") puts original.shuffle I'm not sure how good the shuffle itself is, but the principle is valid :) Regards Dave