如何在Ruby中存储子例程到变量?

ego6inou  于 2023-04-11  发布在  Ruby
关注(0)|答案(2)|浏览(87)

我试图证明你可以在变量中存储子程序(除非你不能)。
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的初学者,只是想学习基本的代码。
qhhrdooz

qhhrdooz1#

你的Python代码可以翻译成Ruby:

def print_sample(str)
  puts str
end

x = method(:print_sample)
str = "Hello"
x.(str)

主要的区别是,因为Ruby中的括号是可选的,所以编写x = print_sample已经调用了该方法。检索一个可以稍后调用的Method对象稍微复杂一些:你必须调用method并将方法名作为符号或字符串传递。(接收者是定义方法的对象)
由于方法对象是常规对象,实际调用方法的语法也略有不同。Ruby提供:

x[str]
x.(str)
x.call(str)

由于x.(str)x.call(str)的语法糖,请参见Method#call
另一种方法是只存储方法名称,并通过send/public_send动态调用方法,例如:

x = :print_sample
str = "Hello"
send(x, str)

在Ruby中,通过方法的(符号化的)名称来引用方法是非常惯用的。

6bc51xsx

6bc51xsx2#

处理示例方法的示例:

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

在这个例子中,我们首先存储了方法,然后将其应用到一个示例中。如果您先有示例,然后想要获取方法,那么就更简单了。假设上面的类定义是Demo,您可以同样很好地执行一个

aDemo = Demo.new("Hi")
y = aDemo.method(:printSample)
y.call("You")

相关问题