In Ruby, how do I write code inside the class so that getter foo and setter self.foo = ... look more similar?

In Ruby, inside the class instance method, we use getter

foo 

and we use the setter

 self.foo = something 

No need to have self. and the other is a way to make them look like it, rather than using something like self.foo as the recipient, as it also looks verbose.

(update: note that getter and setter can simply get or set the instance variable, but they can also do a lot of work, for example, go to the database and check for the record, and if not, create it, etc.)

+3
source share
3 answers

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

The reason you can write foo to use getter is because Ruby will move up the volume when it cannot find a variable with that name, and ultimately find this 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 

To make it clear that you want to access the installer, you must write self.foo = something . This will tell Ruby that you want to execute the foo= method of the self object with the something parameter.

+10
source

If you are ready to break the conventions, you can write your setters using the jQuery style, using the same method for getter and setter, depending on whether there are arguments:

 def foo *args return @foo if args.empty? @foo = args.first end # => nil foo # => nil foo(:bar) # foo = :bar # => :bar foo # => :bar 
+5
source

As far as I know, there is no such way in Ruby. I'm sure this is just how Ruby evaluates expressions.

When setting the value, Ruby will first check to see if there is a local variable in the context that matches the called one. If in your case there is (possibly "foo"), this will be the value used. If there is no such value, then Ruby will try to find the value as a method call (switching to "I" as the caller). If such a method does not exist in the search path, an error occurs.

The need to use "self" in setter is to avoid Ruby setting the value as a local variable, while the lack of using "self" only works in the getter instance when there is no local variable of the same name used in this context . It is probably better and clearer, albeit a little more verbose, to be explicit with your use of the ego in order to avoid confusion as to where the values โ€‹โ€‹come from.

+1
source

Source: https://habr.com/ru/post/1344470/


All Articles