在super中更新ruby hash中的单个值(Update single value in ruby hash from super)

编程入门 行业动态 更新时间:2024-10-11 15:22:26
在super中更新ruby hash中的单个值(Update single value in ruby hash from super)

我在rspec中编写测试,并试图用let声明一些变量。

describe 'my_test' do let(:params) {{ :happy => 1, :sad => 0, }} context 'mixed' do let(:params) {{ :happy => 1, :sad => 1, }} end end

但是后来我看到了super变量如何被写出来,这对长参数列表很方便: http ://myronmars.to/n/dev-blog/2013/02/rspec-2-13-is-released

所以我的问题是,如何覆盖原始散列中的单个值? 我试过搜索,但只能找到覆盖所有值的方法。 像下面这样的东西存在吗?

let(:hash) { super().updatehash('sad', '1') }

I'm writing tests in rspec and am trying to declare some variables with let.

describe 'my_test' do let(:params) {{ :happy => 1, :sad => 0, }} context 'mixed' do let(:params) {{ :happy => 1, :sad => 1, }} end end

But then I saw how variables can be ovewritten with super, which would be convenient for long lists of params: http://myronmars.to/n/dev-blog/2013/02/rspec-2-13-is-released

So my question is, how do I overwrite just a single value in the original hash? I've tried searching but can only find ways to overwrite all values. Does anything like below exist?

let(:hash) { super().updatehash('sad', '1') }

最满意答案

您可以使用散列#合并重载散列变量

let(:hash) { super().merge(:sad => '1') }

它将使用您在散列中提供的键值对来覆盖原始散列中的任何键值以合并它。

如果你想链接到合并的doco,apidock是很好的:

http://apidock.com/ruby/Hash/merge

You can overload hash variables using Hash#merge

let(:hash) { super().merge(:sad => '1') }

it will overwrite any key-values in the original hash with the key-value pairs you provide in the hash to merge over it.

If you'd like a link to the doco for merge, apidock is good:

http://apidock.com/ruby/Hash/merge

更多推荐

本文发布于:2023-08-03 08:54:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1385400.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:ruby   super   hash   single   Update

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!