H
Han Holl
Hello,
The current Hash#invert implementation will silently throw away keys that
have the same value associated with them.
Because I often have many to one hashes, but have preferred keys, I'd like
to propose having an optional arbitrating block, that gets called with
the alternative valuse in an array. Something like this:
class Hash
def invert(&blk)
rsl = {}
arbitrate = {}
each_pair do |k, v|
if rsl.has_key?(v) && block_given?
(arbitrate[v] ||= [rsl[v]]) << k
else
rsl[v] = k
end
end
arbitrate.each_pair do |k,v|
rsl[k] = yield v
end
rsl
end
end
You can call this with something like:
hash.invert {|x| x.find {|el| fields.include?(el)} ||
x.sort_by{|el| el.size}[-1] }
or even the simple:
hash.invert { raise 'This hash is not invertible' }
Does this sound generally useful, or is it just me ?
Cheers,
Han Holl
The current Hash#invert implementation will silently throw away keys that
have the same value associated with them.
Because I often have many to one hashes, but have preferred keys, I'd like
to propose having an optional arbitrating block, that gets called with
the alternative valuse in an array. Something like this:
class Hash
def invert(&blk)
rsl = {}
arbitrate = {}
each_pair do |k, v|
if rsl.has_key?(v) && block_given?
(arbitrate[v] ||= [rsl[v]]) << k
else
rsl[v] = k
end
end
arbitrate.each_pair do |k,v|
rsl[k] = yield v
end
rsl
end
end
You can call this with something like:
hash.invert {|x| x.find {|el| fields.include?(el)} ||
x.sort_by{|el| el.size}[-1] }
or even the simple:
hash.invert { raise 'This hash is not invertible' }
Does this sound generally useful, or is it just me ?
Cheers,
Han Holl