Can I use the same name for a Ruby method parameter and an access method?

Let's say I had a class like this:

class Parser attr_accessor :config, :html def initialize(config, html) @config = config @html = html end ... end 

Is it safe to specify parameters for my initialization method in the same way as attr_accessors? Is this a bad style? What would be a better style?

+4
source share
2 answers

It is absolutely safe, and I do it all the time. However, I think this is the best style for setting the attributes of an object as follows:

 class Parser attr_accessor :config, :html def initialize(config, html) self.config = config self.html = html end ... end 

When you do this, your code will use the setter methods provided by attr_acessor. This way you always have a consistent way of accessing your variables.

+7
source

Yes safe


Ruby implements a lexical definition of the scope, and there are many qualifiers.

This is a pretty reasonable style, I think. It will always be difficult to answer the question, because in some respects the code is easier to read (a variable has a better choice of name) and in some ways more difficult because this name means two different objects, depending on where they are used.

+1
source

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


All Articles