metaprogramming - Ruby list an objects instance methods without it's getters and/or setters -


i'd able list of objects classes instance methods without getters , setters attr_accessor. i've written example , behaves way need to.

i find hard believe there isn't easier way this.

class object   def instance_methods_without_variables     self.class.instance_methods(false).reject {|x| x.to_s.include? "=" } -       self.instance_variables.map {|x| x.to_s[1..-1].to_sym }   end end  class testclass   attr_accessor :var1, :var2    def initialize     @var1 = 'var1'     @var2 = 'var2'   end    def method1() 'method1' end   def method2() 'method2' end end  t = testclass.new p t.instance_methods_without_variables # => [:method1, :method2] 

edit:

after reviewing answers i've opted use following method within class, not object.

def instance_methods_without_variables   self.class.instance_methods(false).reject { |method|     self.instance_variables.any? { |variable| method.to_s.include? variable.to_s[1..-1] } ||     method == __method__   } end 

this works attr_reader & attr_writer

the ruby language has no notion of getters , setters properties. attr_accessor :a_var merely convenient shorthand creating methods :a_var returns value, , :a_var= set value of instance variable @a_var. methods :a_var, , :a_var= no different other method defined in containing class.

so have need partial list of instance methods, excludes ending in =, , have instance variable of same name.

i think have reasonable method implementing behavior, though don't think should implemented on object.


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -