What's the nature of “property” in a Ruby class?

前端 未结 3 1748
攒了一身酷
攒了一身酷 2021-01-19 02:00

I don\'t understand the keywords like attr_reader or property in the following example:

class Voiture 
  attr_reader :name
  attr_         


        
3条回答
  •  感情败类
    2021-01-19 03:05

    Those are class methods, you can add them to a class, or create your own class that has addition methods. In your own class:

    class Voiture
      def self.my_first_class_method(*arguments)
        puts arguments
      end
    end
    

    Or to add to a class:

    Voiture.class_eval do
      define_method :my_second_class_method do |*arguments|
        puts arguments
      end
    end
    

    Once such a class method is defined, you can use it like this:

    class VoitureChild < Voiture
    
        my_first_class_method "print this"
    
        my_second_class_method "print this"
    
    end
    

    There are also ways to do this by adding modules to a class, which is often how rails does such things, such as using a Concern.

提交回复
热议问题