ruby-on-rails - Ruby 方法 Double Splat 与 Hash

标签 ruby-on-rails ruby

处理需要 的方法时已知 参数数量加上选项散列,在双拼音中捕获选项有什么区别/优势吗?

考虑

def method_a(a, **options)
    puts a
    puts options
end

对比
def method_b(a, options = {})
   puts a
   puts options
end

两者等价吗?我认为method_b更具可读性,但我仍然看到很多代码与method_a一起使用。
是否有理由在选项中使用双 splat 当常规(非选项)参数被捕获而没有 splat 时 ?

最佳答案

好吧,这取决于您所说的“已知参数数量”是什么意思,特别是对于关键字参数加上任意数量的其他关键字参数的情况,例如:

def foo(i, keyword_1: "default", **other_keywords)
end

我可以称之为
foo(6, keyword_1: "asd", other: "keyword")

{other: "keyword"}将包含在 other_keywordskeyword_1可以直接作为局部变量访问。

没有 ** splat operator 这种行为实现起来比较麻烦,像这样:
def foo(i, opts={})
 keyword_1 = opts.delete(:keyword_1) || "default"
 # now `opts` is the same as `other_keywords`
end

关于ruby-on-rails - Ruby 方法 Double Splat 与 Hash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58162053/

相关文章:

html - Rails bootstrap flash 不褪色

javascript - 将 CoffeeScript json 对象数据保存在 Rails 变量中

ruby - 未定义的局部变量或方法 ruby

ruby-on-rails - 当我尝试访问 https ://localhost:3000 时收到 Rails 服务器的错误消息

ruby-on-rails - Rspec 的文档在哪里?

php - 我应该用什么编写Web应用程序?它需要能够查询SQL数据库和LDAP数据库

regex - 删除一行中的固定文件扩展名

ruby-on-rails - 表单标签只传递一个值而不是多个

ruby-on-rails - 使用雾 gem 时在哪里定义不同环境的 s3 存储桶名称

ruby-on-rails - Rails选择标签选择值