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

前端 未结 3 1746
攒了一身酷
攒了一身酷 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:06

    That are just class methods. In this example has_foo adds a foo method to an instance that puts a string:

    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
    

提交回复
热议问题