Break OO privacy: Difference between revisions

extended ruby example (instance_variable_get)
m (Added Sidef)
(extended ruby example (instance_variable_get))
Line 962:
 
=={{header|Ruby}}==
Ruby lets you redefine great parts of the object model at runtime and provides several methods to do so conveniently. For a list of all available methods look up the documentation of <code>Object</code> and <code>Module</code> or call informative methods at runtime (<code>puts Object.methods</code>).
In Ruby, you can use <code>.send</code> to send any message to any object, even private ones:
<lang ruby>>> class Example
class Example
>> private
>> def nameinitialize
@private_data = "nothing" # instance variables are always private
>> "secret"
>> end
>> private
>> end
def hidden_method
=> nil
>> "secret"
>> example = Example.new
>> end
=> #<Example:0x101308408>
end
>> example.name
>> example = Example.new
NoMethodError: private method `name' called for #<Example:0x101308408>
p example.private_methods(false) # => [:hidden_method]
from (irb):10
#p example.hidden_method # => NoMethodError: private method `name' called for #<Example:0x101308408>
from :0
>>p example.send(:namehidden_method) # => "secret"
p example.instance_variables # => [:@private_data]
=> "secret"</lang>
p example.instance_variable_get :@private_data # => "nothing"
p example.instance_variable_set :@private_data, 42 # => 42
p example.instance_variable_get :@private_data # => 42
</lang>
 
=={{header|Scala}}==
10

edits