scope - The most annoying quirk of class methods in ruby ever -


can spot problem in following code?

module f   def f(x)     return x*x   end end  class test3   include f   def self.ok(x)     return f(2*x)   end end 

how one?

class test1    def f(x)      return x*x    end    def test1.ok(x)      return f(2*x)    end end 

or maybe this?

class test2    def self.ok(x)      def f(x)        return x*x      end      return f(2*x)    end end 

this not intuitive @ all. why can't ruby find 'f' in of these cases?

like many object-oriented languages, ruby has separation between methods in class context , in instance context:

class example   def self.a_class_method     "i'm class method!"   end    def an_instance_method     "i'm instance method!"   end end 

when calling them using native context works:

example.a_class_method example.new.an_instance_method 

when calling them in wrong context errors:

example.new.a_class_method # => no such method example.an_instance_method # => no such method 

since instance related class can this:

example.new.class.a_class_method # => works! 

that's done inside instance methods need use class methods. class methods aren't able utilize instance methods except if there's instance in play. when deciding make method, need consider context in used. if it's instance related, especially if uses @-style instance variables, it's instance method. if it's generic utility method intended used independent of particular instance, it's class method.

in other languages class methods called "static" methods, they're stand-alone basically, in ruby relate class itself, special object, can little confusing @ times.

that's why paying attention presence of self in definition important.


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -