J
Just Another Victim of the Ambient Morality
Okay, the following line will print the number 0 correctly:
puts 0
Embarrassingly enough, I come from a C/C++ background (that's not the
embarrassing part), so I thought of this as a cast from the FIXNUM type, 0,
to a string type, "0" (this is the embarassing part). Of course, after the
following test failed to evaluate to true:
if 0 =~ /0/
puts "Yes!"
end
...it occurred to me that Ruby is dynamically typed. The implementation
of puts simply called the to_s method of the FIXNUM 0 and, hence, prints as
it does. Obviously, the regular expression operator =~ does no such thing,
or the test above would evaluate to true.
My question is this: why doesn't =~ call to_s? Surely, it needed the
string data of the parameter passed into it, right? How could it have not
called to_s? Why wouldn't we want it to? If "puts x" works with any x with
a to_s defined, is it unreasonable to expect the same convenience with our
regular expression operators? Or any operation on strings, for that matter?
I'm just wondering, since I'm a funny sort who like to understand
things...
Thanks for your responses!
puts 0
Embarrassingly enough, I come from a C/C++ background (that's not the
embarrassing part), so I thought of this as a cast from the FIXNUM type, 0,
to a string type, "0" (this is the embarassing part). Of course, after the
following test failed to evaluate to true:
if 0 =~ /0/
puts "Yes!"
end
...it occurred to me that Ruby is dynamically typed. The implementation
of puts simply called the to_s method of the FIXNUM 0 and, hence, prints as
it does. Obviously, the regular expression operator =~ does no such thing,
or the test above would evaluate to true.
My question is this: why doesn't =~ call to_s? Surely, it needed the
string data of the parameter passed into it, right? How could it have not
called to_s? Why wouldn't we want it to? If "puts x" works with any x with
a to_s defined, is it unreasonable to expect the same convenience with our
regular expression operators? Or any operation on strings, for that matter?
I'm just wondering, since I'm a funny sort who like to understand
things...
Thanks for your responses!