Thanks guys,
Daniel, I started out with something similar to that, although yours
is alot better, but then thought it would be nice to have something
like random 'a'..'z' aswell or even random Thing.new(1)..Thing.new(6)
. Which i'll probably not need anyway so i'll 'borrow' yours if I may.
Ha! I had to ri Range to actually find out how it supported Ranging Things. Now I know. That's neat.
Devin, thanks, 1) will do!, i'm going to go and have a look at the
pickaxe to see why.
Yes, singleton methods are the elixir of life.
2) I was vaguely aware that creating the arrays
could be a bad idea for big ranges but couldn't work out how to get
the nth member of a range except by doing something likevalue = range.first
for 1..n
value = value.succ
end
Yeah, that's probably right. I imagine Range#each looks like this
class Range
def each
value = self.first
loop do
yield value
break if value == self.last
value = value.succ
end
end
end
which seemed a bit nasty or by getting the entries which seemed quite
nice in light of the chapter I read about duck typing
Yeah, I guess don't bother changing it until you need to get a random thing from a very large Range, in which case, you might want to provide further optimizations for things like Integer. You can still have fun with duck typing my way, though!
class Range
def rand
if self.first.respond_to? :rand_to
self.first.rand_to(self.last)
else
# normal implementation goes here
end
end
end
class Array
def rand
# normal implementation goes here
end
end
class Integer
def rand_to(last)
self + rand(last - self)
end
end
...
foo.rand #where foo is whatever
Ben (Ruby Newbie)
Oh, but the good kind. The kind that's not afraid to dive deep into the language features. (Honestly, I fall under RubyNuby compared to most of the people on this list. I'm just vocal for the time being.)
Devin