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 name the parameters to my initializer method the same as the attr_accessors? Is it bad style? What would be a better style?
It is totally safe to do this and I do it all the time. However, I think that's it's a better style to set your object attributes like this:
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 that your variables are accessed.
Ruby implements lexical scoping and there are many scope qualifiers.
It's a fairly reasonable style, I guess. The question will always be a bit hard to answer because in some respects the code is easier to read (the variable has the best choice of name) and in some ways harder, because a given name means two different objects depending on where it is used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With