Close
Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

PIVOTAL LABS
Happy Left Handers' Day

Interestings

private attributes in ruby

Did you know that you can make an attribute access private?

class Foo
  def initialize(stuff)
    @stuff = stuff
  end

  private

  attr_reader :stuff
end

or

class Foo
  attr_reader :stuff
  private :stuff

  def initialize(stuff)
    @stuff = stuff
  end
end

And now, Foo.new("x").stuff will raise an error!

Comments
  1. richardkmichael says:

    Good tip. Though, I prefer to do this by putting the `attr_reader` declaration below `private`. I find this avoids confusion when quickly skimming the class’ public interface and also keeps everything “private” together.

    `class Foo

    private

    attr_reader :stuff
    `

  2. Ken Mayer says:

    I’ve updated the post to make it clear that both ways work.

Post a Comment

Your Information (Name required. Email address will not be displayed with comment.)

* Copy This Password *

* Type Or Paste Password Here *