Skip to content

Instantly share code, notes, and snippets.

@nakajima
Created May 27, 2009 01:05
Show Gist options
  • Save nakajima/118398 to your computer and use it in GitHub Desktop.
Save nakajima/118398 to your computer and use it in GitHub Desktop.
Guide on how to invoke a method in Ruby.
Here's an example of a few different ways to call a method on a Ruby object.
If you're a beginner, try running the code above to watch it in action.
If you're not a beginner, go ahead and tear me a new one for whichever techniques I forgot ;)
- Pat
# Ways to invoke a method in Ruby
def demonstrate(label, &block)
print label + ': '
result = yield Class.new { def invoke!; :correct end }.new
puts result == :correct ? "Pass!" : "Fail (#{result})"
end
demonstrate "Directly calling it" do |object|
object.invoke!
end
demonstrate "Using Object#send" do |object|
object.send :invoke!
end
demonstrate "Using Object#method, then call" do |object|
object.method(:invoke!).call
end
demonstrate "Unbinding the method, then rebinding and calling" do |object|
m = object.class.instance_method(:invoke!)
m.bind(object).call
end
demonstrate "Using instance_eval" do |object|
object.instance_eval { invoke! }
end
# Feel free to fork and tell me what I forgot.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment