In Ruby, there is the "method" method, which creates a method object that you can then treat as a Proc. This is useful if you wish to do metaprogramming:
def foobar(method_as_a_string)
2.method(method_as_a_string).call(2)
end
foobar("+")
=> 4
foobar("-")
=> 0
However, normally, if you want to do such meta-programming, you would use send
instead of method...
def foobar(method_as_a_string)
2.send(method_as_a_string, 2)
end
foobar("+")
=> 4
foobar("-")
=> 0
What is the point of the "method" method then in Ruby?
A method in Ruby is a set of expressions that returns a value. With methods, one can organize their code into subroutines that can be easily invoked from other areas of their program. Other languages sometimes refer to this as a function. A method may be defined as a part of a class or separately.
In ruby, the concept of object orientation takes its roots from Smalltalk. Basically, when you call a method, you are sending that object a message. So, it makes sense that when you want to dynamically call a method on an object, the method you call is send . This method has existed in ruby since at least 1.8.
In short: no, Ruby does not support nested methods.
Ruby allows method names and other identifiers to contain such characters.) Method names may contain letters, numbers, an _ (underscore or low line) or a character with the eight bit set. Method names may end with a ! (bang or exclamation mark), a ? (question mark) or = equals sign.
You can pass a method
result to a block, and it will call the method passing the iteratee as arguments.
For example, this wouldn't work:
[1,2,3].each(&:puts)
because it's calling 1.puts
, 2.puts
, etc. But this would:
[1,2,3].each(&method(:puts))
Another example:
arr, result = [1,2,3], []
arr.each &result.method(:push)
result # => [1,2,3]
Another useful thing is using it to find the source location of a method:
Someclass.method(:some_method).source_location
# => this will give you the file & line where it's defined
This is a very helpful trick when you're working with gems and want to quickly glance at their source code
A Method
object provides for all sorts of introspection and metaprogramming, including:
How and what you use those powers for is up to you.
For Cary, below:
"cat".method(:count).receiver
# => "cat"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With