Ruby类中“属性”的本质是什么?

我不理解以下示例中的attr_readerproperty等关键字:

 class Voiture attr_reader :name attr_writer :name property :id, Serial property :name, String property :completed_at, DateTime end 

他们是如何工作的? 我该如何创建自己的? 它们是function,方法吗?

 class MyClass mymagickstuff :hello end 

这只是类方法。 在此示例中, has_foofoo方法添加到放置字符串的实例:

 module Foo def has_foo(value) class_eval <<-END_OF_RUBY, __FILE__, __LINE__ + 1 def foo puts "#{value}" end END_OF_RUBY end end class Baz extend Foo has_foo 'Hello World' end Baz.new.foo # => Hello World 

这些是类方法,您可以将它们添加到类中,或者创建自己的具有附加方法的类。 在你自己的class上:

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

或者添加到class级:

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

一旦定义了这样的类方法,就可以像这样使用它:

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

还有一些方法可以通过向类添加模块来实现这一点,这通常是rails执行此类操作的方式,例如使用Concern

你会想要修补类Module 。 这就是像attr_reader这样的方法所在的位置。

 class Module def magic(args) puts args.inspect end end class A magic :hello, :hi end #=> [:hello, :hi] 

正如The Tin Man所提到的,猴子修补基础课程可能很危险。 考虑它就像过去的时间旅行并在过去添加一些东西。 只需确保您添加的内容不会覆盖其他某些事件,否则您可能会回到与您离开的Ruby脚本/时间轴不同的Ruby脚本/时间轴。