In Ruby, how to write code inside a class so that getter foo and setter self.foo = … look more similar?

前端 未结 3 1473
面向向阳花
面向向阳花 2020-12-30 17:18

In Ruby, inside a class\'s instance method, we use a getter by

foo

and we use a setter by

self.foo = something
3条回答
  •  不思量自难忘°
    2020-12-30 17:40

    As far as I know, there isn't a way around this in Ruby. I'm pretty confident this is simply how Ruby evaluates expressions.

    When given a value, Ruby will first check if there is a local variable within the context which matches the one being called. If there is (perhaps 'foo' in your case), that will be the value used. If there is no such value, then Ruby will try to look up the value as a method call (falling through to "self" as the caller). If no such method exists in the look up path, an error will be raised.

    The need to use "self" in the setter is to avoid Ruby setting the value as a local variable, while the lack of the use of "self" only works in the getter instance when there is no local variable of the same name being used in that context. It is probably better and clearer, albeit slightly more verbose, to be explicit with your use of self as to avoid confusion about where values are coming from.

提交回复
热议问题