有什么方法和属性在Ruby中的区别? [英] What is the difference between Methods and Attributes in Ruby?

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

问题描述

你能给我一个例子吗?

推荐答案

属性是对象的特定属性。方法是一个对象的功能。

Attributes are specific properties of an object. Methods are capabilities of an object.

在Ruby中的所有实例变量(属性)默认情况下私人。这意味着你没有实例本身的范围之外访问它们。
访问属性的唯一方法是使用访问方法。

In Ruby all instance variables (attributes) are private by default. It means you don't have access to them outside the scope of the instance itself. The only way to access the attribute is using an accessor method.

class Foo
  def initialize(color)
    @color = color
  end
end

class Bar
  def initialize(color)
    @color = color
  end

  def color
    @color
  end
end

class Baz
  def initialize(color)
    @color = color
  end

  def color
    @color
  end

  def color=(value)
    @color = value
  end
end

f = Foo.new("red")
f.color # NoMethodError: undefined method ‘color’

b = Bar.new("red")
b.color # => "red"
b.color = "yellow" # NoMethodError: undefined method `color=' 

z = Baz.new("red")
z.color # => "red"
z.color = "yellow"
z.color # => "yellow"

由于这是一个非常commmon行为,Ruby提供一些方便的方法来定义存取方法: attr_accessor中 attr_writer attr_reader

Because this is a really commmon behavior, Ruby provides some convenient method to define accessor methods: attr_accessor, attr_writer and attr_reader.

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

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