Ruby 赋值语法
一个愚蠢的语法问题:
如果赋值运算符实际上是一个函数,就像
def value=(x)
@value = x
end
左侧操作数和“=”之间没有空格,那么为什么可以将赋值设置为 test.value = x(带空格),但方法定义不能写成:
def value = (x)
@value = x
end
带空格。这只是解析器规定的语法吗?
A silly, syntactical question:
If the assignment operator is really a function, like
def value=(x)
@value = x
end
without a space between the left-hand operand and the "=", then why can the assignment be made as test.value = x (with a space), but the method definition cannot be written as:
def value = (x)
@value = x
end
with the space. Is this simply syntax dictated by the parser?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
def
后面需要跟一个函数名称的标记,后面可以选择跟一个参数列表。参数列表上的括号是可选的(例如,def value= x
是一个适当的定义)。def value = (x)
看起来像def
后跟两个标记,然后是一个参数列表,但不会解析。def
needs to be followed by a token for the function name, optionally followed by an argument list. The parenthesis on the argument list is optional (e.g.,def value= x
is an appropriate definition).def value = (x)
looks likedef
followed by two tokens and then an argument list, which does not parse.这就是解析器/解释器的魔力。
当解释器看到赋值时,就会寻找匹配的方法。
我在这方面同意你的观点(几乎),我认为分配应该始终是
some.value= x
(“value”和“=”之间没有空格)。Scala 做了类似的事情,但使用下划线
def value_= ( x: X )
That's parser/interpreter magic.
When the interpreter sees the assignment looks for a matching method.
I agree with you in this regard ( almost ), I think the assignment should be
some.value= x
( without space between 'value' and '=' ) always.Scala does something similar but uses an underscore
def value_= ( x: X )