-
-
Save michaeldv/118457 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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. | |
demonstrate "Using method_missing ;-)" do |object| | |
object.instance_eval "def method_missing(*args); self.invoke!; end" | |
object.hello? | |
end | |
demonstrate "Using method alias ;-)" do |object| | |
object.class.class_eval "alias :run! :invoke!" | |
object.run! | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment