ruby - 哈希解构

标签 ruby hash splat

您可以使用 splat 运算符解构数组。

def foo(arg1, arg2, arg3)
  #...Do Stuff...
end
array = ['arg2', 'arg3']
foo('arg1', *array)

但是有没有办法为选项类型的优点破坏散列?

def foo(arg1, opts)
  #...Do Stuff with an opts hash...
end
opts = {hash2: 'bar', hash3: 'baz'}
foo('arg1', hash1: 'foo', *opts)

如果不是原生 ruby​​,Rails 是否添加了类似的东西?

目前我大致在做这个

foo('arg1', opts.merge(hash1: 'foo'))

最佳答案

是的,有一种方法可以解构散列:

def f *args; args; end
opts = {hash2: 'bar', hash3: 'baz'}
f *opts  #=> [[:hash2, "bar"], [:hash3, "baz"]]

问题是您想要的实际上根本不是解构。你正试图从

'arg1', { hash2: 'bar', hash3: 'baz' }, { hash1: 'foo' }

(请记住 'arg1', foo: 'bar' 只是 'arg1', { foo: 'bar' } 的简写)

'arg1', { hash1: 'foo', hash2: 'bar', hash3: 'baz' }

根据定义,这就是合并(注意周围的结构——散列——如何仍然存在)。而解构来自

'arg1', [1, 2, 3]

'arg1', 1, 2, 3

关于ruby - 哈希解构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15191364/

相关文章:

pandas - 匿名数据/替换名称

javascript - 正则表达式从 HTML 内容解析哈希 URL

java - SHA 哈希似乎无法正常工作

ruby - Ruby 中加星标的变量是什么?

javascript - splat over JavaScript 对象(用 new )?

ruby-on-rails - 访问授权和访问 token 之间的区别

ruby-on-rails - 计算在 heroku 上运行的应用程序的内存占用

ruby-on-rails - 如何使用 Ruby 按字母顺序排序标题列表,忽略 "The"?

ruby - 有没有办法让 "Vitamin B12"不在 "Vitamin B6"前面?

ruby - 我怎样才能 splattify 一个匿名对象,以便我可以在它上面使用 &method ?