【问题标题】:What does a splat operator do when it has no variable name?splat 运算符在没有变量名时会做什么?
【发布时间】:2013-08-01 02:52:18
【问题描述】:

我正在浏览 Camping 代码库时看到一个带有 splat 的构造函数,像这样使用:

class Fruit 
  def initialize(*)
  end
end

我尝试在此站点和 Google 上查找“没有变量名的 splat”,但除了关于 splat 与 *some_var 这样的变量名一起使用的信息外,我找不到任何其他信息,但不是没有。我尝试在 repl 上玩这个,我尝试了类似的东西:

class Fruit 
  def initialize(*)
      puts *
  end
end

Fruit.new('boo')

但是会遇到这个错误:

(eval):363: (eval):363: compile error (SyntaxError)
(eval):360: syntax error, unexpected kEND
(eval):363: syntax error, unexpected $end, expecting kEND

如果这个问题还没有被问过,有人能解释一下这个语法的作用吗?

【问题讨论】:

    标签: ruby


    【解决方案1】:

    通常,像这样的 splat 用于指定方法未使用但超类中相应方法使用的参数。这是一个例子:

    class Child < Parent
      def do_something(*)
        # Do something
        super
      end
    end
    

    这就是说,在超类中调用这个方法,将原始方法的所有参数传递给它。

    来源:Ruby 编程 1.9 (Dave Thomas)

    【讨论】:

    • 这只是 Josnidhin 提到的一个特例。
    【解决方案2】:

    它的行为类似于 *args 但你不能在方法体中引用 then

    def print_test(a, *)
      puts "#{a}"
    end
    
    print_test(1, 2, 3, 'test')
    

    这将打印 1。

    【讨论】:

      猜你喜欢
      • 2013-08-19
      • 1970-01-01
      • 2020-09-09
      • 2019-05-19
      • 2019-05-30
      • 2020-10-22
      • 2012-05-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多