Ruby Assignment Syntax

扶醉桌前 提交于 2019-12-04 01:18:57

问题


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?


回答1:


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 like def followed by two tokens and then an argument list, which does not parse.




回答2:


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 )



来源:https://stackoverflow.com/questions/4963427/ruby-assignment-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!