ruby - 为什么这个 splat 方法调用在 Ruby 中不起作用?

标签 ruby

def method(a, b='a', c, *d)
  [a,b,c, d]
end

p method(1,2,3,4)

不工作,我不明白为什么,如果我们删除 b 参数一切正常。语法规则说您可以将具有默认值的参数放在 splat 参数之前。

最佳答案

只要具有默认值的变量可以被解释为(唯一的)splat 的初始元素,具有默认值的变量和 splat 变量就可以存在并共存。

因此,这些都可以工作:

def good(a = :a, b);      [a,b];    end
def good(a = :a, *b);     [a,b];    end
def good(a, b = :b, *c);  [a,b,c];  end

但这些不会:

def bad(*a, b = :b);          [a,b];    end  # default after the splat
def bad(a = :a, b, c = :c);   [a,b,c];  end  # parsing would need two splats
def bad(a = :a, b, *c);       [a,b,c];  end  # parsing would need two splats
def bad(*a, b = :b, c);       [a,b,c];  end  # default after the splat

(老实说,我不知道是什么实现细节阻止 Ruby 在 splat 后立即接受默认值,前提是没有歧义。但我猜这是为了避免在 splat 上循环两次而不是一次,即性能,并且可能还有其他原因可能与 Ruby 计算方法的元数的方式有关。)

关于ruby - 为什么这个 splat 方法调用在 Ruby 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20801426/

相关文章:

ruby - 构建网络框架

ruby - Rubocop 规则 : Never use 'do' with multi-line 'while

ruby - 编写 ruby​​ 代码的正确方法是什么?

ruby - 为什么 datamapper 不更新记录/检测脏度?

jquery - Ruby on Rails + Jquery : Saving data from draggable lists

ruby-on-rails - vim omnicomplete with ruby​​ 只能部分工作

ruby-on-rails - 服务器安装遇到错误:无法在任何源中找到 pg-0.17.1 (Bundler::GemNotFound)

ruby - 在匿名 block 中产生

ruby - 是否有接受上传文件、执行某些操作并让用户下载结果的网站模板?

ruby - 在 Ruby 中使用 '+' 文件 IO 模式替换文件中的一行