“属性”的性质是什么?在Ruby类中? [英] What's the nature of "property" in a Ruby class?

查看:172
本文介绍了“属性”的性质是什么?在Ruby类中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白以下示例中的 attr_reader 属性的关键字:

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

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

?如何创建自己的?它们是功能,方法吗?

How do they work? How can I create my own? Are they functions, methods?

class MyClass 
    mymagickstuff :hello
end


推荐答案

这只是类方法。在此示例中, has_foo 向放置了字符串的实例添加了 foo 方法:

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

这篇关于“属性”的性质是什么?在Ruby类中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆