Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Private references to instance variables with attr_accessor available #73

Closed
ghost opened this issue Feb 15, 2012 · 1 comment
Closed

Comments

@ghost
Copy link

ghost commented Feb 15, 2012

Wondering which the preferred method...

Reference the instance variable with the "@" notation from within the class:

class Sample
  attr_reader :color

  def initialize(color)
    @color = color
  end

  def demo
    @color
  end
end

or referencing the instance variable with the getter representation:

class Sample
  attr_reader :color

  def initialize(color)
    @color = color
  end

  def demo
    color
  end
end

Likewise the setter variant:

Reference the instance variable with the "@" notation from within the class:

class Sample
  attr_accessor :color

  def initialize(color)
    @color = color
  end

  def demo
    @color = "awesome color"
  end
end

or referencing the instance variable with the getter representation:

class Sample
  attr_accessor :color

  def initialize(color)
    @color = color
  end

  def demo
    self.color = "awesome color"
  end
end
@bbatsov
Copy link
Collaborator

bbatsov commented Feb 22, 2012

It depends - if mutator methods enforce some invariants on an attribute I'd definitely use them. Same goes for reader methods that return a defensive copy of an attribute. Otherwise - attribute access is a little bit faster than method calls (although they might be inlined).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant