Eduard Bondarenko
Eduard Bondarenko

Reputation: 363

Why is changing an attribute allowed?

I am wondering why Ruby allows us to change a read-only attribute.

class Test
  attr_reader :h

  def initialize
    @h = {}
  end
end

t = Test.new
t.h # => {}
t.h['name'] = 'somename'
t.h # => {"name"=>"somename"}

Can we forbid a user to do it?

Upvotes: 0

Views: 67

Answers (3)

mralexlau
mralexlau

Reputation: 2003

To elaborate on @Sergio's comment, the reason you can change @h is because attr_reader :h is shorthand for:

def h
  @h
end

So defining this method has no bearing on what you can do to set the instance variable @h.

Upvotes: 0

idmean
idmean

Reputation: 14895

h is read-only. You can't change the value stored in h. But Ruby is object-oriented and everything is an object, and h is just a reference (an object-pointer). And nothing prevents you from modifying the object to which h points.

Upvotes: 0

Vasfed
Vasfed

Reputation: 18494

Your h field is the reference to the hash, but you're changing the hash itself, not the reference.

Upvotes: 3

Related Questions