ruby – 如何匹配包含数组的哈希忽略数组元素的顺序?
发布时间:2020-12-17 03:03:20 所属栏目:百科 来源:网络整理
导读:我有两个包含数组的哈希.在我的例子中,数组元素的顺序并不重要.是否有一种简单的方法来匹配RSpec2中的这些哈希? { a: [1,2] }.should == { a: [2,1] } # how to make it pass? 附: 数组的匹配器忽略了顺序. [1,2].should =~ [2,1] # Is there a similar ma
我有两个包含数组的哈希.在我的例子中,数组元素的顺序并不重要.是否有一种简单的方法来匹配RSpec2中的这些哈希?
{ a: [1,2] }.should == { a: [2,1] } # how to make it pass? 附: 数组的匹配器忽略了顺序. [1,2].should =~ [2,1] # Is there a similar matcher for hashes? 解 解决方案适合我.最初由tokland建议,有修复. RSpec::Matchers.define :match_hash do |expected| match do |actual| matches_hash?(expected,actual) end end def matches_hash?(expected,actual) matches_array?(expected.keys,actual.keys) && actual.all? { |k,xs| matches_array?(expected[k],xs) } end def matches_array?(expected,actual) return expected == actual unless expected.is_a?(Array) && actual.is_a?(Array) RSpec::Matchers::BuiltIn::MatchArray.new(expected).matches? actual end 要使用匹配器: {a: [1,2]}.should match_hash({a: [2,1]}) 解决方法
我写了一个自定义匹配器:
RSpec::Matchers.define :have_equal_sets_as_values do |expected| match do |actual| same_elements?(actual.keys,expected.keys) && actual.all? { |k,xs| same_elements?(xs,expected[k]) } end def same_elements?(xs,ys) RSpec::Matchers::BuiltIn::MatchArray.new(xs).matches?(ys) end end describe "some test" do it { {a: [1,2]}.should have_equal_sets_as_values({a: [2,1]}) } end # 1 example,0 failures (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |