0

Are instance variables private? I hear both claims that they are private and that they do not have access specifier [sic] though they behave as private. Can instance variables be made private?

sawa
  • 165,429
  • 45
  • 277
  • 381
Rohan Pujari
  • 788
  • 9
  • 21
  • Instances variable can only be accessed by the instance, that's why they are called instances variables. This makes them as private as can be, the only way to make them more private would be if they couldn't be accessed at all, which doesn't make sense. They are "more private" than private fields in Java, for example, because private fields in Java can be accessed by the instance *and* all other instances of the same class, whereas instance variables in Ruby can be accessed *only* by the instance and not by *any* other object, even including other instances of the same class. – Jörg W Mittag Jun 13 '14 at 11:28

1 Answers1

0

There is a limited amount of 'privateness' granted to ruby instance variables, you can always access them from the outside through e.g. instance_variable_get (a public method) as outlined in this question. So depending on your desired level of 'privateness' the answer would be "they are private", "they are protected" or "they cannot be really private"

Community
  • 1
  • 1
Patru
  • 4,481
  • 2
  • 32
  • 42