Break OO privacy: Difference between revisions

Content added Content deleted
m (Added Sidef)
(extended ruby example (instance_variable_get))
Line 962: Line 962:


=={{header|Ruby}}==
=={{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
<lang ruby>
class Example
>> private
>> def name
def initialize
@private_data = "nothing" # instance variables are always private
>> "secret"
>> end
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
>> example.send(:name)
p example.send(:hidden_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}}==
=={{header|Scala}}==