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
=> 30

Yay! 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?

1 Upvotes

5 comments sorted by

View all comments

Show parent comment

3

u/materialdesigner Mar 27 '14

some of the other "okay" things in metaprogramming:

  • dynamic method generation/definition not using method_missing
  • send
  • reflection