First a question: Why is
p (1..10).to_a
interpreted as
(p (1..10)).to_a >> 1..10
instead of
p ((1..10).to_a) >> [1, ..., 10]
It gave me a hard time to figure this out, especially as "nil.to_a"
(nil is the result of p(..)) has a meaning and doesn't throw an error.
I would have expected that, if I leave a SPACE between the method name
and the open parenthesis, it is NOT taken as the argument to "p" but
instead the "." has a higher precedence. At least this would be a
useful assumption IMHO.
But my actual and original question is another one. In Squeak
Smalltalk, I can send #shuffle to an Array (or any
SequenceableCollection I think) to randomize an array. Is there a
similar built-in mehtod in Ruby? It's of course easy to add (see
below - code improvements are welcomed!), but it's so useful I'd like
to see it being part of the built-in stuff.
class Array
def shuffle
clone.shuffle!
end
def shuffle!
len = length
(0...len).each {|i|
j = rand len
self[i], self[j] = self[j], self[i]
}
self
end
end
p ((1..100).to_a.shuffle)
BTW, is there just one global random number generator?
bye
--
Stefan Matthias Aust \/ Truth Until Paradox