ruby - Ruby 中的方法和属性有什么区别?

标签 ruby attributes methods

你能举个例子吗?

最佳答案

属性只是一个快捷方式。如果您使用 attr_accessor 创建属性,Ruby 只需声明一个实例变量并为您创建 getter 和 setter 方法。

既然你问了一个例子:

class Thing
    attr_accessor :my_property

    attr_reader :my_readable_property

    attr_writer :my_writable_property

    def do_stuff
        # does stuff
    end
end 

下面是您将如何使用该类:

# Instantiate
thing = Thing.new

# Call the method do_stuff
thing.do_stuff

# You can read or write my_property
thing.my_property = "Whatever"
puts thing.my_property

# We only have a readable accessor for my_readable_property
puts thing.my_readable_property 

# And my_writable_propety has only the writable accessor
thing.my_writable_property = "Whatever"

关于ruby - Ruby 中的方法和属性有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1194585/

相关文章:

ruby-on-rails - Controller Action 中未定义的方法新

ruby - 根据数组在另一个数组中的存在情况对数组重新排序

c# - ASP.NET MVC 使用 UIHint 属性生成 DropDownList

java - 在另一个类中调用方法时出现空指针

c#CompareTo()方法

android - Android webview的loadData和loadDataWithBaseURL有什么区别

ruby - Ruby 中类似 __<original_name>__ 的方法

ruby - 如何要求一个中文名为ruby的文件?

ruby-on-rails - Rails - 'send' 和 'try' 的混合

c# - 实现 FlagsAttribute 时将 Enum 解析为 Enum