I want to store several different methods in an array in Ruby. Suppose I want to store the type
method twice:
[type, type]
doesn't store two entries of type
in an array; it executes type
twice, and stores the results in the array. how do I refer explicitly to the method object itself?
(this is just a simplified version of what I really want.)
EDIT: on second thoughts, it bothers me that the solution proposed below avoids the problem by passing the name of the method. how do you pass the method object itself? for example, what if you pass [:type, :type] to a method that has an alternative resolution for type? how can you pass the type method object itself?
In Ruby, (almost) every variable is in fact a reference/pointer to an object, e.g. will give [0, 1, 23, 42] because a and b are pointing to the same object. So in fact, you are using pointers all the time.
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.
We call (or invoke) the method by typing its name and passing in arguments. You'll notice that there's a (words) after say in the method definition. This is what's called a parameter. Parameters are used when you have data outside of a method definition's scope, but you need access to it within the method definition.
The use of :: on the class name means that it is an absolute, top-level class; it will use the top-level class even if there is also a TwelveDaysSong class defined in whatever the current module is.
If you want to store a method rather than the result of calling a method or just the message you'd send to invoke it, you need to use the method
method on the owning object. So for example
"hello".method(:+)
will return the + method of the object "hello", so that if you call it with the argument " world", you'll get "hello world".
helloplus = "hello".method(:+)
helloplus.call " world" # => "hello world"
If you're thinking about doing method references in Ruby, you're doing it wrong.
There is a built-in method in Ruby called method
. It will return a proc version of the method. It is not a reference to the original method, though; every call to method
will create a new proc. Changing the method won't affect the proc, for example.
def my_method
puts "foo"
end
copy = method(:my_method)
# Redefining
def my_method
puts "bar"
end
copy.call
# => foo
When you want to store pieces of code, and don't want to use regular methods, use procs.
stack = [proc { do_this }, proc { do_that }]
stack.each {|s| s.call }
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