dblack@candle.superlink.net graced us by uttering:
Tim Hammerquist wrote:
- Ruby’s object system is beautiful, elegant, and practical. It’s
much more “pure” (in the Smalltalk definition) than either Perl
or Python and allows you to retroactively modify pre-existing
instances of an object at runtime by modifying their class. (See
http://www.unr.nevada.edu/~tahammer/hack/ruby/ for an example).
Or even by adding methods to the object itself:
str = “Ruby is an extraordinary language.”
def str.vowels
scan(/[aeiou]/)
end
p str.vowels
=> [“u”, “i”, “a”, “e”, “a”, “o”, “i”, “a”, “a”, “u”, “a”, “e”]
Yes, but even Python can do that!
Perhaps I didn’t explain well:
What if you need a certain method on a whole bunch of pre-existing
objects. Do you want to manually add the method to each object, and
then possibly have to add it to more, later?
str = “Ruby is an extraordinary language.”
class String
def vowels
scan(/[aeiou]/)
end
end
p str.vowels
[“u”, “i”, “a”, “e”, “a”, “o”, “i”, “a”, “a”, “u”, “a”, “e”]
p FILE.vowels
[“i”]
p ENV[“PATH”].vowels
[“o”, “e”, “i”, “i”, “u”, “o”, “a”, “i”, “u”, “i”, “u”, “i”, “i”, “u”,
“i”, “a”, “a”, “i”, “u”, “a”, “e”, “i”, “u”, “a”, “e”, “o”, “i”, “o”,
“o”, “e”, “i”, “o”, “e”, “i”, “o”, “e”, “i”, “o”, “o”, “e”, “i”]
Furthermore, suppose you decide later on that you’d like #vowels to
return "y"s also. Simply redefine the method!
class String
def vowels
scan(/[aeiouy]/)
end
end
p str.vowels
[“u”, “y”, “i”, “a”, “e”, “a”, “o”, “i”, “a”, “y”, “a”, “u”, “a”, “e”]
Yes, this would be better implemented with a separate function, rather
than risk breaking existing code that expects only the 5 primary vowels.
Or add an optional boolean argument to #vowels indicating you want the
extra characters matched, etc., etc. =) However, if you absolutely MUST
modify your program at runtime, at least we know Ruby lets us…
This still doesn’t mean this functionality is desirable to you, and some
other languages might consider this a Bad Thing ™. But I’d sure hate
to need this functionality and be using a language that doesn’t provide
for it!
HTH
Tim Hammerquist
···
–
His ignorance is painful.
– Cell, Dragonball Z