r/learnruby • • Mar 26 '14
Ruby's unbreakable rules?
What are they?
As a heavy python user, I expect that python modules will never modify built-in types. We're not allowed to.
>>> int.__add__ = lambda self,other: self - other
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'int'This keeps rule-breaking me in line, and even though I do know how to do this, it's a serious hack and I'll be chased down the road with flaming pitchforks, so I don't. Of course the very first thing I had to do after getting into ruby was:
>> Fixnum.send(:define_method, "+", Proc.new{ |other| self - other })
=> :+
>> 33 + 3
=> 30Yay! I can break everything in the language. I mean once I do this, random functions start raising IndexError unpredictably. Bats sleep right side up. Yellow is blue. Ruby is COBOL. So I assume the limitations are cultural. What are the common rubyist expectations about rules meant never to be broken in a language so lispy that everything can be redefined?
View all comments
Show parent comment
1
u/[deleted] Mar 26 '14
The trouble is I don't know how much metaprogramming is common, so I have no sense of what is an innocuous change and what isn't. It's obvious that reassigning + to - is going to cause problems, but less obvious whether I can add an optional argument to attr_accessor and carefully wrap it for the default case.
I have no sense of whether I'm breaking something because I don't yet know all the ways that some method or object can be accessed and used. I was hoping for some guidelines like "don't pass procs to methods that expect lambdas because the stack will unwind and you will die."
I don't know. I don't know what I don't know in this language.