I am trying to prove that you can store subroutines inside a variable (unless you can't). Any chance that I just have this code all wrong?
I have this code from Python that does what I want to do
def printSample(str)
puts str
end
x = printSample
str = "Hello"
x(str)
expected output:
Hello
I am a beginner in Ruby and just trying to learn basic codes.
CodePudding user response:
Your Python code can be translated to Ruby as:
def print_sample(str)
puts str
end
x = method(:print_sample)
str = "Hello"
x.(str)
The main difference is that because parentheses in Ruby are optional, writing x = print_sample
would already invoke the method. Retrieving a Method object that you can call later is a little more involved: you have to call method
and pass the method name as a symbol or string. (the receiver being the object the method is defined in)
And because method objects are regular objects, the syntax for actually calling the method is also slightly different. Ruby provides:
x[str]
x.(str)
x.call(str)
With x.(str)
being syntactic sugar for x.call(str)
, see Method#call
Another approach is to just store the method name and to invoke the method dynamically via send
/ public_send
, e.g.:
x = :print_sample
str = "Hello"
send(x, str)
Referring to methods via their (symbolized) name is quite idiomatic in Ruby.
CodePudding user response:
Example for handling an instance method:
class Demo
def initialize(s); @s = s; end
def printSample(str); puts(@s str); end
end
x = Demo.instance_method(:printSample)
# x is now of class UnboundMethod
aDemo = Demo.new("Hi")
# Use x
x.bind(aDemo).call("You") # Outputs: HiYou
In this example, we first stored the method, and then applied it to an instance. If you have the instance first and want to fetch the method later, it is even simpler. Assuming the class definition of Demo
from above, you can equally well do a
aDemo = Demo.new("Hi")
y = aDemo.method(:printSample)
y.call("You")