gpt4 book ai didi

ruby - 哈希解构

转载 作者:数据小太阳 更新时间:2023-10-29 08:18:40 27 4
gpt4 key购买 nike

您可以使用 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/

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