【问题标题】:#Ruby Tk passing method/functions as arguments#Ruby Tk 将方法/函数作为参数传递
【发布时间】:2016-11-02 00:39:55
【问题描述】:

我解释一下:

我想知道如何将方法或函数作为参数传递。

例如,在 Python 中将是:

from MyFile import MyClass

MyClass().my_method_click(function)  # without parentheses

在本例中,在 Python 中,您发送的函数或方法不包含 括号,如果我这样做:

from MyFile import MyClass

MyClass().my_method_click(function())  # with parentheses

我调用函数但不发送它。

Ruby 中,当您调用方法或函数时,您可以使用 or 没有括号。

如果我在 Ruby 中这样做:

require_relative "MyClass"

MyClass.new.my_method_click(function) # without parentheses

直接调用而不发送。

当然是针对一个Button,即当我点击它时,运行这个操作。

我如何在 Ruby 中做到这一点?

谢谢!

【问题讨论】:

  • 您的问题不清楚。你谈论方法和函数,好像它们是可以互换的,但方法和函数是非常不同的东西。方法属于对象,但它们本身不是对象。函数对象。 Ruby 没有“函数”的概念。根据你的意思确切地,“函数”的角色可以由以下任何一个来扮演:一个Proc,一个响应call的对象,一个响应@987654326的对象@,或响应call to_proc的对象。

标签: python ruby-on-rails ruby methods tk


【解决方案1】:

基本上,您希望传递一个可运行的代码块。我还没有研究过 Python,但我相信它也支持闭包。

无论如何,在 Ruby 中,传递可运行代码的“通用”方式是使用块(lambdas 和 procs)。

function = lambda { # your code }
MyClass.new.my_method_click(function)

# or a shorter way
MyClass.new.my_method_click(-> { # your code })

# to run a block
def my_method_click(&block)
    #you can either `yield` from your receiving method
    yield

    # or call `.call` method on your lambda/proc instance
    block.call
end

您还可以获取类方法的实例或使用Method.new 创建一个新方法。但是,您最终会处理绑定并绑定到正确的实例类型等。因此,使用Lambdas 和Procs 会容易得多。

【讨论】:

    猜你喜欢
    • 2015-04-07
    • 2014-04-09
    • 2015-05-01
    • 2013-09-11
    • 2010-10-06
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 2016-10-14
    相关资源
    最近更新 更多