分配符号如何工作-Ruby [英] how does the assignment symbol work - Ruby

查看:118
本文介绍了分配符号如何工作-Ruby的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中,如果我只是分配一个局部变量.

In Ruby if i just assign a local variable.

sound = "bang". 

main.sound=("bang")方法吗?如果是这样,那么在哪里以及如何定义方法"sound =?或该工作如何进行?如果没有,实际上是什么情况?

is that a main.sound=("bang") method? if so, where and how is that method "sound=" being defined? or how is that assignment working? if not, what is actually happening?

我知道对于setter方法,您会说x.sound =("bang").并且您正在使用参数"bang"在对象"x"上调用方法"sound =.并且您正在创建一个实例变量"sound".

i know that for a setter method you would say x.sound=("bang"). and you are calling the method "sound=" on the object "x" with the argument "bang". and you are creating an instance variable "sound".

我可以想象所有这些.但是当您在主要"对象中分配变量时则不会.据我所知,这不是Object类的实例变量...还是它?我很困惑.

and i can picture all of that. but not when you assign a variable in the "main" object. as far as i know it isn't an instance variable of the Object class... or is it? I'm so confused.

推荐答案

在大多数编程语言(包括Ruby)中,赋值是一种奇怪的野兽.它不是方法或函数,它的作用是将名称(由于它在赋值的左侧,所以也称为左值)与值相关联.

In most programming languages, Ruby included, assignment is a strange beast. It is not a method or function, what it does is associate a name (also called an lvalue since it's left of the assignment) with a value.

Ruby增加了定义名称以=结尾的方法的能力,可以使用赋值语法来调用这些方法.

Ruby adds the ability to define methods with names ending in = that can be invoked using the assignment syntax.

属性访问器只是创建其他方法的方法,这些方法可获取并分配类的成员变量.

Attribute accessors are just methods that create other methods that fetch and assign member variables of the class.

所以基本上您可以通过3种方式查看作业:

So basically there are 3 ways you see assignment:

  • 原始=运算符
  • 名称以=
  • 结尾的方法
  • 属性访问器为您生成的方法(这些方法以=结尾)

这篇关于分配符号如何工作-Ruby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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