Reputation: 24873
I'm working with a Ruby API that takes a series of boolean switches, something along the lines of:
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.
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?
(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)
Thanks,
-- Matt
Upvotes: 2
Views: 1667
Reputation: 9225
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}
Upvotes: 4
Reputation: 35803
Here is one solution:
switches={}
true_vals.each do |v|
switches[v]=true
end
false_vals.each do |v|
switches[v]=false
end
Upvotes: 1