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

理解[ClassOne,ClassTwo].each(&:my_method)[重复]

  •  14
  • scubabbl  · 技术社区  · 17 年前

    可能重复:
    What does map(&:name) mean in Ruby?

    我在看一个铁路列车员,看到了这个代码。

    [Category, Product].(&:delete_all)
    

    关于清理数据库。

    我在IRC上询问了这条线,并被告知

    (&:delete_all)
    

    是一条捷径

    {|model| model.delete_all}
    

    我用以下方法进行了测试

    class ClassOne
      def class_method
        puts 1
      end
    end
    
    class ClassTwo
      def class_method
        puts 2
      end
    end
    
    [ClassOne, ClassTwo].each(&:class_method)
    

    我收到一个错误消息,说

    Wrong Argument type Symbol (expected Proc)
    

    我也试过了

    one = ClassOne.new
    two = ClassTwo.new
    
    [one, two].each(&:class_method)
    

    但这仍然失败了。

    如果我将其修改为

    [one, two].each{|model| model.class_method}
    

    一切按预期进行。

    那么,什么是 &:delete_all 真的吗?医生说 delete_all 这是一种方法,所以我对这里发生的事情感到困惑。

    2 回复  |  直到 8 年前
        1
  •  20
  •   Alex M    17 年前

    这依赖于Ruby 1.9扩展,可以在1.8中通过包含以下内容来完成:

    class Symbol
        def to_proc
          proc { |obj, *args| obj.send(self, *args) }
        end
    end
    

    我相信Rails在 ActiveSupport .

        2
  •  3
  •   Zach    17 年前

    这是Ruby的一些Rails特定补丁, symbol to proc .

    推荐文章