02.20
I was puzzled tonight concerning Ruby and its behavior regarding Standard Objects. For instance, redefining True is perfectly legal in Python:
>>> def is_True_true():
... if True:
... print "True is true"
... else:
... print "True is false"
...-
>>> is_True_true()
True is true
>>> True=False
>>> is_True_true()
True is false
Boolean values are in Python two constant objects. You can redefine them, but their scope becomes local:
>>> is_True_true()
True is true
>>> def evil():
... True=False
...-
>>> evil()
>>> is_True_true()
True is true
This behavior may be a little confusing sometimes:
>>> type(True)
<type 'bool'>
>>> True=12
>>> type(True)
<type 'int'>
>>> False=12
>>> False == True
True
Like in Ruby, booleans are implemented in Python using the Signleton pattern:
The values False and True will be singletons, like None. Because the type has two values, perhaps these should be called “doubletons”?
See PEP 285
In Ruby however, these objects cannot be changed.truefor instance is (the single) instance of classTrueClass, and an exception is raised whenever one tries to modify them. It is also the case forfalse,nil, etc.
Hence a question: why some attributes are locked in Ruby? Dave Thomas in Programming Ruby argues:
bq. After all, you probably don’t want to change the meaning oftruehalfway through your program (except perhaps if you’re a politician).
And what if I was a politician? Since every class is open in Ruby, doesn’t that mean that it allows the programmer to do whatever he wants? Is it more dangerous fortrueto be modifiable compared to+?irb(main):001:0> class Fixnum irb(main):002:1> def +(arg) irb(main):003:2> return self-arg irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> 1+1 => 0Ruby doesn’t try to prevent the coder to write stupid code, as
CorC++does by using types for instance. So why a selected set of special objects doesn’t follow this philosophy?
No Comment.
Add Your Comment