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

前端 未结 3 1456
面向向阳花
面向向阳花 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

    Since local scope takes precedence, when you say foo = something, a local variable foo will be created and assigned the contents of something.

    The reason you can write foo in order to use the getter is because Ruby will move up in scope when it can't find a variable with that name and it will eventually find the method.

    If there is a local variable with the same name as the getter method, Ruby will use its value instead:

    class Foo
    
      attr_accessor :foo
    
      def initialize
        @foo = :one
      end
    
      def f
        foo = :two
        foo
      end
    end
    
    Foo.new.f
    # => :two
    

    In order to make it clear that you want to access the setter, you must write self.foo = something. That will tell Ruby you want to execute the foo= method on the self object with something as parameter.

提交回复
热议问题