How to Find Class of + in Ruby -
the design philosophy of ruby amazing. did 1 + 2 , got 3. managed make this: 1.+(2) # => 3.
as cool was, wanted test out class method on + method.
+.class => syntaxerror: (irb):14: syntax error, unexpected '.' +.class ^ and then:
+().class => nomethoderror: undefined method `+@' nilclass:class while:
+(2).class nomethoderror: undefined method `+@' fixnum:class why +(2).class fixnum , not integer? try again +(2.to_i).class , same error appears +(2).class.
but key question: how find class of + method?
1 + 2 calling + method on 1 2 argument, same 1.+(2).
however, because of precedence, +(2).class calling (2).class first, returning instance of class, calling nonexistent +@ method, unary plus method exists numeric. can test typing (+(2)).class, returns fixnum 1 expect. source of error +().class, because () returns nil, , class of nil nilclass, doesn't have +@ method.
tl;dr: because precedence made leading + evaluate last, +@.
the + method on object of class method, other method on object. however, typing + calls method instead of returning it, because matz saw in dream programming language returns methods instead of calling them doesn't run. can have method returned calling method method method name, so: 1.method(:+). can make method object tell class is: 1.method(:+).class.
Comments
Post a Comment