代码之家  ›  专栏  ›  技术社区  ›  Peter

Ruby中的方法指针

  •  16
  • Peter  · 技术社区  · 15 年前

    我想在Ruby的数组中存储几个不同的方法。假设我想把 type 方法两次:

    [type, type]
    

    不存储两个条目 类型 在数组中;它执行 类型 两次,然后存储 结果 在数组中。如何显式地引用方法对象本身?

    (这只是我真正想要的简化版。)

    编辑:再想一想,下面提出的解决方案通过传递方法的名称来避免这个问题,这让我很困扰。如何传递方法对象本身?例如,如果将[:type,:type]传递给对类型具有可选分辨率的方法,该怎么办?如何传递类型方法对象本身?

    3 回复  |  直到 12 年前
        1
  •  32
  •   Chuck    15 年前

    如果要存储方法而不是调用方法的结果,或者只存储要调用方法而发送的消息,则需要使用 method 所属对象的方法。例如

    "hello".method(:+)
    

    将返回对象“hello”的+方法,这样,如果用参数“world”调用它,您将得到“hello world”。

    helloplus = "hello".method(:+)
    helloplus.call " world" # => "hello world"
    
        2
  •  13
  •   August Lilleaas    15 年前

    如果你想用Ruby做方法引用,那你就错了。

    Ruby中有一个内置方法 method . 它将返回该方法的proc版本。但是,它不是对原始方法的引用;每次调用 方法 将创建新进程。例如,更改方法不会影响过程。

    def my_method
      puts "foo"
    end
    
    copy = method(:my_method)
    
    # Redefining
    def my_method
      puts "bar"
    end
    
    copy.call
    # => foo
    

    当您想要存储代码片段,而不想使用常规方法时,请使用procs。

    stack = [proc { do_this }, proc { do_that }]
    stack.each {|s| s.call }
    
        3
  •  1
  •   Josh Matthews    15 年前
    [:type, :type].collect { |method_name| self.send(method_name) }
    

    或者,如果方法是对象的一部分:

    method = obj.method(:type)
    values = [method.call, method.call]