等号 ('=') 放在方法定义中的方法名称之后有什么作用? [英] What does the equal ('=') symbol do when put after the method name in a method definition?

查看:36
本文介绍了等号 ('=') 放在方法定义中的方法名称之后有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在截屏视频中看到了这一点,只是想知道="符号在这种情况下的作用.

I saw this in a screencast and was just wondering what the '=' symbol does in this case.

def express_token=(token)
...
end

如果是这样的话,我会理解 -

I would understand if it were something like this -

def express_token(token = nil) 

以上(第二个代码片段)表示将 nil 设置为 tokens 参数的默认值.但是,在第一个代码片段中,="在括号之外.

The above (second code snippet) means setting nil as the default value of the tokens parameter. However, in the first code snippet, '=' is outside the brackets.

推荐答案

该代码段定义了一个 Virtual属性(或setter"方法)使express_token"看起来像一个属性,即使它只是方法的名称.例如:

That snippet defines a Virtual Attribute (or a "setter" method) so that "express_token" looks like an attribute, even though it's just the name of the method. For example:

class Foo
  def foo=(x)
    puts "OK: x=#{x}"
  end
end
f = Foo.new
f.foo = 123 # => 123
# OK: x=123

请注意,对象f"没有名为foo"的属性或实例变量(也不需要),因此foo="方法只是语法糖,用于允许看起来像赋值的方法调用.还要注意,这样的 setter 方法总是返回它们的参数,而不管任何 return 语句或最终值.

Note that the object "f" has no attribute or instance variable named "foo" (nor does it need one), so the "foo=" method is just syntactic sugar for allowing a method call that looks like an assignment. Note also that such setter methods always return their argument, regardless of any return statement or final value.

如果您正在定义顶级 setter 方法,例如,在irb"中,那么由于向 Object 类隐式添加了方法,该行为可能会有些混乱.例如:

If you're defining a top-level setter method, for example, in "irb", then the behavior may be a little confusing because of the implicit addition of methods to the Object class. For example:

def bar=(y)
  puts "OK: y=#{y}"
end
bar = 123 # => 123, sets the variable "bar".
bar # => 123
Object.new.bar = 123 # => 123, calls our method
# OK: y=123
Object.public_methods.grep /bar/ # => ["bar="]

这篇关于等号 ('=') 放在方法定义中的方法名称之后有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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