My first ruby program:
ruby 1.6.4 (2001-06-04) [i586-linux]
-----8<-----8<-----8<-----8<-----8<-----8<-----8<-----8<-----8<-----8<-----
#! /usr/bin/env ruby
class Shuffle
def initialize(data)
raise(TypeError, "not an array") if data.type != Array
@store = data
@mark = Array.new
@marked = 0
end
def each
while @marked < @store.length
while @mark[i = rand(@store.length)]
end
@mark[i] = true
@marked += 1
yield @store[i].gsub(/ /, '\\ ')
end
end
end
Shuffle.new(ARGV).each {|s| print "#{s} " }
-----8<-----8<-----8<-----8<-----8<-----8<-----8<-----8<-----8<-----8<-----
Is there no way to prototype Shuffle.new()? I've to handle the
wrong type on my own.
And String#gsub seems to have a strange sense of humor regarding
the priorities in the replacement string.
I'd like to use something like
astr.gsub(/\s/, '\\\&')
irb(main):001:0> astr='abc xzy'
"abc xzy"
irb(main):002:0> astr.gsub(/\s/, '\\\&')
"abc\\&xzy"
irb(main):003:0> astr.gsub(/(\s)/, '\\\1')
"abc\\1xzy"
irb(main):004:0> astr.gsub(/(\s)/, '\\1')
"abc xzy"
In Perl you can write
$a =~ s/(\s)/\\$1/g;