将Ruby数组转换为键值对的散列,其中值为常量

时间:2023-01-24 21:43:16

I'm working with a Ruby API that takes a series of boolean switches, something along the lines of:

我正在使用Ruby API,它采用一系列布尔开关,类似于:

validate({ :can_foo => true, :can_bar => false, :can_baz => true, ... })

I'm writing a series of tests to verify that the API is behaving as it should, so I need to construct a lot of sets of switches. It seemed wasteful to continue to type :foo => true all the time, so I figured I'd write a little Ruby ditty to convert an array to this structure, e.g.

我正在编写一系列测试来验证API是否正常运行,因此我需要构建许多开关集。继续键入:foo =>似乎是浪费时间,所以我想我应该写一个小Ruby小调来将数组转换为这个结构,例如。

true_vals  = %w( these are my true  items )
false_vals = %w( these are my false items )

convert  = lambda{ |arr, truthiness| arr.inject({}){ |res, key| res.update(key=>truthiness) } }
falsify  = lambda{ |arr| convert.call(arr, false) }
truthify = lambda{ |arr| convert.call(arr, true)  }

validate( truthify.call(true_vals).merge( falsify.call(false_vals) ) )

Does that seem any better than simply typing out a long list of :sym => [true|false] pairs? Is there a better way to do this?

这似乎比简单地输入一长串:sym => [true|false]对更好吗?有更好的方法吗?

(I started with true_vals.inject({}){ |res, key| res.update(key=>true) } but that doesn't feel DRY enough; I'd have to copy-paste & s/true/false/ to do the false ones; and I'm doing it many many times so a lambda seems reasonable)

(我从true_vale .inject({}){|res, key| res.update(key=>true)}开始,但感觉不够干;我必须复制粘贴& s/true/false;我做了很多次所以a看起来很合理

Thanks,

谢谢,

-- Matt

——马特

2 个解决方案

#1


4  

cs = {  true =>   [:y, :yes], 
        false =>  [:n, :no] }
Hash[cs.map{ |k, vs| vs.map{ |v| [v, k] } }.flatten(1)]
#=> {:y=>true, :yes=>true, :no=>false, :n=>false}

#2


1  

Here is one solution:

这里有一个解决方案:

switches={}
true_vals.each do |v|
    switches[v]=true
end
false_vals.each do |v|
    switches[v]=false
end

#1


4  

cs = {  true =>   [:y, :yes], 
        false =>  [:n, :no] }
Hash[cs.map{ |k, vs| vs.map{ |v| [v, k] } }.flatten(1)]
#=> {:y=>true, :yes=>true, :no=>false, :n=>false}

#2


1  

Here is one solution:

这里有一个解决方案:

switches={}
true_vals.each do |v|
    switches[v]=true
end
false_vals.each do |v|
    switches[v]=false
end