我试图证明你可以在变量中存储子程序(除非你不能)。
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)
预期输出:
你好
- 我是Ruby的初学者,只是想学习基本的代码。
我试图证明你可以在变量中存储子程序(除非你不能)。
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)
预期输出:
你好
2条答案
按热度按时间qhhrdooz1#
你的Python代码可以翻译成Ruby:
主要的区别是,因为Ruby中的括号是可选的,所以编写
x = print_sample
已经调用了该方法。检索一个可以稍后调用的Method对象稍微复杂一些:你必须调用method
并将方法名作为符号或字符串传递。(接收者是定义方法的对象)由于方法对象是常规对象,实际调用方法的语法也略有不同。Ruby提供:
由于
x.(str)
是x.call(str)
的语法糖,请参见Method#call
另一种方法是只存储方法名称,并通过
send
/public_send
动态调用方法,例如:在Ruby中,通过方法的(符号化的)名称来引用方法是非常惯用的。
6bc51xsx2#
处理示例方法的示例:
在这个例子中,我们首先存储了方法,然后将其应用到一个示例中。如果您先有示例,然后想要获取方法,那么就更简单了。假设上面的类定义是
Demo
,您可以同样很好地执行一个