Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Created April 13, 2012 04:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JoshCheek/2373788 to your computer and use it in GitHub Desktop.
Save JoshCheek/2373788 to your computer and use it in GitHub Desktop.
private attr_writer
class Klass
def initialize(number)
self.number = number
end
attr_reader :number
private
attr_writer :number
end
Klass.instance_methods false # => [:number]
Klass.new(123).number # => 123
begin
klass = Klass.new 123
klass.number = 456
rescue
$! # => #<NoMethodError: private method `number=' called for #<Klass:0x007fe0fb887c80 @number=123>>
end
@jpablobr
Copy link

shouldn't it be:

 def initialize(value)
    self.number = value
  end

That will give you:

Klass.instance_methods false # => [:number]
Klass.new(123).number # => 123

and still private :) in the sense that:

begin
  klass = Klass.new 123
  klass.number = 456
rescue
  pp $! #<NoMethodError: private method `number=' called for #<Klass:0x9e1e908 @number=123>>
end

@JoshCheek
Copy link
Author

Thanks :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment