Fastest/One-liner way to list attr_accessors in Ruby?

前端 未结 6 842
忘了有多久
忘了有多久 2020-12-02 14:16

What\'s the shortest, one-liner way to list all methods defined with attr_accessor? I would like to make it so, if I have a class MyBaseClass, any

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 15:15

    Class definitions

    class MyBaseClass
      attr_writer :an_attr_writer
      attr_reader :an_attr_reader
    
      def instance_m
      end
    
      def self.class_m
      end
    end
    
    class SubClass < MyBaseClass
      attr_accessor :id
    
      def sub_instance_m
      end
    
      def self.class_sub_m
      end
    end
    

    Call as class methods

    p SubClass.instance_methods - Object.methods    
    p MyBaseClass.instance_methods - Object.methods
    

    Call as instance methods

    a = SubClass.new
    b = MyBaseClass.new
    
    p a.methods - Object.methods
    p b.methods - Object.methods
    

    Both will output the same

    #=> [:id, :sub_instance_m, :id=, :an_attr_reader, :instance_m, :an_attr_writer=]
    #=> [:an_attr_reader, :instance_m, :an_attr_writer=]
    

    How to tell which are writer reader and accessor?

    attr_accessor is both attr_writer and attr_reader

    attr_reader outputs no = after the method name

    attr_writer outputs an = after the method name

    You can always use a regular expression to filter that output.

提交回复
热议问题