Ruby Assignment Syntax

Stupid, syntactic question:

If the assignment operator is really a function, for example

def value=(x) @value = x end 

without a space between the left operand and "=", then why the assignment can be performed as test.value = x (with a space), but the method definition cannot be written as:

 def value = (x) @value = x end 

with space. Is this just the syntax dictated by the parser?

+6
syntax ruby language-design
source share
2 answers

def must follow a token for the function name, optionally followed by a list of arguments. The bracket in the argument list is optional (for example, def value= x is the corresponding definition). def value = (x) looks like def followed by two tokens, and then an argument list that is not parsed.

+6
source share

That is the parser / interpreter of magic.

When the interpreter sees that the assignment is looking for a matching method.

I agree with you in this regard (almost), I think the assignment should be some.value= x (no spaces between the "value" and "=").

Scala does something similar, but uses the underscore def value_= ( x: X )

+1
source share

All Articles