Ruby setter方法语法method =(value)-与Java比较 [英] Ruby setter method syntax method=(value) - Comparison to Java

查看:101
本文介绍了Ruby setter方法语法method =(value)-与Java比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,亲爱的stackoverflowers:)

Hello dear stackoverflowers :)

我来自Java,对getter的语法有疑问(如果它实际上只是语法问题).

I came from Java and have one doubt about the syntax of getters (if it's really just a syntax issue).

在Java中,您将有一个

In java you would have a setter like

private void setName(value) {
    variableName = value;
}

谁将值作为参数并更改其中的实例变量.

who would take value as an argument and change the instance variable inside it.

在ruby中,当我显式定义setter时(由于约束原因),我需要使用set_name =(value)还是使用语法set_name(value)会相同?换句话说,方法名称末尾的= =可以做其他任何事情,或者仅仅是语法(例如!和?).

In ruby, when I explicitly define a setter (due to constraint reasons), I need to use set_name=(value) or if I use the syntax set_name(value) would be the same? In other words, the = in the end of the method name does anything else or it's just syntax (like ! and ?).

赞:

def set_name=(value)
    @name = value
end

或者这个:

def set_name(value)
    @name = value
end

预先感谢您的关注.

亚历克斯

推荐答案

方法名称中的尾随=将方法标识为设置方法/更改方法.当您在Ruby中说这个话:

The trailing = in the method name identifies the method as a setter/mutator method. When you say this in Ruby:

o.p = v

您实际上是在说:

o.send(:p=, v)

所以o.p = v只是在o中调用p=方法的一种奇特的方式.这就是为什么这样的事情:

so o.p = v is just a fancy way of calling the p= method in o. That's why things like this:

's'.pancakes = 11

给您一个NoMethodError异常,该异常抱怨's'没有pancakes=方法:字符串不(不幸地)没有pancakes=方法.

gives you a NoMethodError exception that complains about 's' not having a pancakes= method: Strings don't (unfortunately) have pancakes= methods.

在您的情况下,您根本不会使用set_name,而您会使用name=方法:

In your case, you wouldn't use set_name at all, you'd have a name= method:

def name=(value)
  @name = value
end

以及可能的name方法作为访问器/获取器:

and possibly a name method as an accessor/getter:

def name
  @name
end

这篇关于Ruby setter方法语法method =(value)-与Java比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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