gpt4 book ai didi

ruby - splat 运算符在没有变量名时会做什么?

转载 作者:数据小太阳 更新时间:2023-10-29 06:46:28 26 4
gpt4 key购买 nike

我在浏览 Camping 代码库时看到一个带有 splat 的构造函数,如下所示:

class Fruit 
def initialize(*)
end
end

我试着在这个网站和谷歌上查找“splat with no variable name”,但除了关于 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

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

最佳答案

通常这样的 splat 用于指定方法未使用但父类(super class)中相应方法使用的参数。这是一个例子:

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

这表示,在父类(super class)中调用此方法,将提供给原始方法的所有参数传递给它。

来源:Ruby 1.9 编程(Dave Thomas)

关于ruby - splat 运算符在没有变量名时会做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17984476/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com