Send an unknown method call: Difference between revisions
Content added Content deleted
(→Tcl: Added implementation) |
(→{{header|Ruby}}: Show that Object#send can call private methods.) |
||
Line 87: | Line 87: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
You may replace :foo, :bar or "foo" with any expression that returns a Symbol or String. |
|||
<lang ruby>class Example |
<lang ruby>class Example |
||
def foo |
def foo |
||
Line 98: | Line 100: | ||
symbol = :foo |
symbol = :foo |
||
Example.new.send symbol # => 42 |
Example.new.send symbol # => 42 |
||
Example.new.send( :bar, 1, 2 ) { |x,y| x+y } # => 3 |
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}}== |
=={{header|Tcl}}== |