Send an unknown method call: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|Ruby}}: fixed alignment)
(Task rewrite but maintaining original intent.)
Line 1: Line 1:
{{draft task|Object oriented}}
{{draft task|Object oriented}}


Send a message to an object without knowing the name of the message. See also [[Respond to an unknown method call]].
Invoke an object method where the name of the method to be invoked can be generated at run time.

;Cf:
* [[Respond to an unknown method call]].


=={{header|Ruby}}==
=={{header|Ruby}}==


<lang ruby>
<pre>
class Example
class Example
def foo
def foo
Line 17: Line 20:
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</lang>
</pre>


=={{header|Python}}==
=={{header|Python}}==
String literal "foo" may be replaced by any expression resulting in a string

<lang python>
<pre>
class Example(object):
class Example(object):
def foo(self):
def foo(self):
return 42
return 42
getattr(Example(), "foo")() # => 42
getattr(Example(), "foo")() # => 42</lang>
</pre>

Revision as of 22:34, 27 August 2011

Send an unknown method call is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Invoke an object method where the name of the method to be invoked can be generated at run time.

Cf

Ruby

<lang ruby> class Example

 def foo
   42
 end
 def bar(arg1, arg2, &block)
   block.call arg1, arg2
 end

end

symbol = :foo Example.new.send symbol # => 42 Example.new.send( :bar, 1, 2 ) { |x,y| x+y } # => 3</lang>

Python

String literal "foo" may be replaced by any expression resulting in a string <lang python> class Example(object):

    def foo(self):
            return 42

getattr(Example(), "foo")() # => 42</lang>