与Ruby访问器方法混淆 [英] confused with Ruby accessor methods

查看:82
本文介绍了与Ruby访问器方法混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很困惑如何在Ruby类中命名方法名称。如果我创建一个访问器,如:
attr_accessor:name

i'm really confused how to name method names in Ruby classes. if i create an accessor like: attr_accessor :name

它创建了以下方法:
name

name =

it creates to methods: name and name=

但是当我调用第二个方法时,在名称和 =之间留有空格会有效

but when i call the second method with a whitespace between the 'name' and '=' it works

'n.name ='和'n.name ='都可以。

'n.name=' and 'n.name =' both works.

我读到Ruby忽略空格的地方。那么,为什么我用空格调用由我编写的方法不起作用?

i read somewhere that Ruby ignores whitespaces. Well then, why a method written by me does not work when i call it with whitespace?

def getname
end

def getname end

如果我这样打电话,那是行不通的。为什么?
t.get名称

if i call this way, it doesn't work. why? t.get name

我并不感到惊讶,因为它不起作用。但是我对setter方法(name =)的工作方式感到困惑吗?

i'm not surprised as it does not work. but i'm confused how the setter method (name=) works then?

预先感谢。

推荐答案

设置器在Ruby中很特殊。

Setters are special in Ruby.


实际上,定义以等号结尾的方法名称可以使该名称有资格出现在赋值的左侧。

In fact, defining a method name ending in an equals sign makes that name eligible to appear on the left-hand side of an assignment.

来自 http://www.ruby-doc.org/ docs / ProgrammingRuby / html / tut_classes.html

赋值在Ruby中定义为:

Assignments are defined in Ruby as:


赋值语句将变量或属性的左侧(左值)设置为引用右侧的值(右值)。

An assignment statement sets the variable or attribute on its left side (the lvalue) to refer to the value on the right (the rvalue).

$ b来自 http://www.ruby的
$ b

-doc.org/docs/ProgrammingRuby/html/tut_expressions.html

所以 n.name = 直接调用设置器 name =

n.name = 使用这种特殊的二传手,是因为它以 = 结尾您可以将其用作分配中的左值(即,它可以出现在左侧)。

n.name = is using this special treatment of setters by the fact that it ends in an =, to make it so that you can use it as the lvalue (that is, it can appear on the left side) in an assignment.

这篇关于与Ruby访问器方法混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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