0

I was looking at this code and was trying to figure what def status=(status) means. I have never seen that before.

class Tweet
attr_accessor :status

def initialize(options={})
self.status = options[:status]
end

def public?
self.status && self.status[0] != "@"
end

def status=(status)
@status = status ? status[0...140] : status
end
end
4

3 回答 3

4

That is a setter - the method to be called when you say thing.status = whatever.

Without such a method, saying thing.status = whatever would be illegal, since that syntax is merely syntactic sugar for calling the setter.

于 2013-05-07T00:45:21.217 回答
4

我会尝试用外行的方式回答这个问题,因为我在开始时不明白这一点。

假设您希望Tweet该类具有一个属性status。现在您想更改该属性,因为它隐藏在类中,所以您不能。您可以与类中的任何内容进行交互的唯一方法是创建一个方法来执行此操作:

def status=(status)
  @status = status # using @ makes @status a class instance variable, so you can interact with this attribute in other methods inside this class
end

伟大的!现在我可以这样做了:

tweet = Tweet.new
tweet.status = "200" # great this works
# now lets get the status back:
tweet.status # blows up!

我们无法访问该status变量,因为我们还没有定义这样做的方法。

def status
  @status # returns whatever @status is, will return nil if not set
end

现在tweet.status也可以了。

有这方面的简写:

attr_setter :status #like the first method
attr_reader :status # like the second one
attr_accessor :status # does both of the above
于 2013-05-07T01:41:53.300 回答
1

def foo 这意味着与始终意味着完全相同的东西:定义一个名为foo.

def initialize

定义一个名为 的方法initialize

def public?

定义一个名为的方法public?

def status=

定义一个名为的方法status=

而已。这里绝对没有什么特别的。定义名称以=符号结尾的方法时没有什么神奇之处。

调用名称以=符号结尾的方法时,就会发生魔法。基本上,您可以在=符号和方法名称的其余部分之间插入空格。因此,不必像这样调用方法

foo.status= 42

你可以这样称呼它:

foo.status = 42

这使它看起来像一个任务。注意:它也被视为另一种赋值;就像所有其他形式的赋值一样,赋值表达式计算为被赋值的值,这意味着在这种情况下方法的返回值被忽略

于 2013-05-07T08:32:52.497 回答