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> |
<lang ruby> |
||
class Example |
|||
⚫ | |||
def initialize |
|||
@private_data = "nothing" # instance variables are always private |
|||
⚫ | |||
end |
|||
⚫ | |||
⚫ | |||
def hidden_method |
|||
=> nil |
|||
⚫ | |||
⚫ | |||
⚫ | |||
=> #<Example:0x101308408> |
|||
end |
|||
>> example.name |
|||
⚫ | |||
⚫ | |||
p example.private_methods(false) # => [:hidden_method] |
|||
from (irb):10 |
|||
⚫ | |||
from :0 |
|||
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}}== |