Send an unknown method call: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|Python}}: added evaluation results)
m (→‎{{header|Ruby}}: fixed alignment)
Line 16: Line 16:


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
</pre>
</pre>



Revision as of 22:19, 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.

Send a message to an object without knowing the name of the message. See also Respond to an unknown method call.

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

Python

class Example(object):
     def foo(self):
             return 42
 
getattr(Example(), "foo")()      # => 42