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
1 Answer