|
|
|
|
|
by zwp
1954 days ago
|
|
Maybe I misunderstand your use of the word "function" here, but in addition to Proc/lambda you can certainly reference a method, pass that around, return it, call it? See: * https://ruby-doc.org/core-2.7.1/Method.html
* https://ruby-doc.org/core-2.7.1/Object.html#method-i-method
$ irb
2.3.3 :001 > p = Kernel.method(:puts)
=> #<Method: Kernel.puts>
2.3.3 :002 > p.call "Hello"
Hello
=> nil
2.3.3 :003 > def run_a_method(meth, *args)
2.3.3 :004?> meth.call(*args)
2.3.3 :005?> end
=> :run_a_method
2.3.3 :006 > run_a_method(p, "Hi!")
Hi!
=> nil
2.3.3 :007 >
ps. this also works with the "to_proc" operator (&) so you can do this: [1, 2, 3].each(&Kernel.method(:puts))
(but I wouldn't necessarily recommend this since it's not very readable, at least to my eyes). |
|