Anonymous user
Send an unknown method call: Difference between revisions
→{{header|Ruby}}: Show that Object#send can call private methods.
(→Tcl: Added implementation) |
(→{{header|Ruby}}: Show that Object#send can call private methods.) |
||
Line 87:
=={{header|Ruby}}==
You may replace :foo, :bar or "foo" with any expression that returns a Symbol or String.
<lang ruby>class Example
def foo
Line 98 ⟶ 100:
symbol = :foo
Example.new.send symbol # => 42
Example.new.send( :bar, 1, 2 ) { |x,y| x+y } # => 3
args = [1, 2]
Example.new.send( "bar", *args ) { |x,y| x+y } # => 3</lang>
Object#send can also call protected and private methods, skipping the usual access checks. Ruby 1.9 adds Object#public_send, which only calls public methods.
{{works with|Ruby|1.9}}
<lang ruby>class Example
private
def privacy; "secret"; end
public
def publicity; "hi"; end
end
e = Example.new
e.public_send :publicity # => "hi"
e.public_send :privacy # raises NoMethodError
e.send :privacy # => "secret"</lang>
=={{header|Tcl}}==
|