Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to use the same name for a Ruby method parameter and an accessor method?

Tags:

ruby

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?

like image 937
dan Avatar asked Feb 25 '23 12:02

dan


2 Answers

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.

like image 105
dontangg Avatar answered May 05 '23 13:05

dontangg


Yes, it's safe


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.

like image 20
DigitalRoss Avatar answered May 05 '23 15:05

DigitalRoss