Module: Enumerable
- Defined in:
- lib/sublime_dsl/core_ext/enumerable.rb
Instance Method Summary collapse
-
#keyed_by ⇒ Object
Returns a hash
{ key => element }, wherekeyis the value returned by the block when passedelement.
Instance Method Details
#keyed_by ⇒ Object
Returns a hash { key => element }, where key is the value returned by the block when passed element.
Raises an exception if two elements return the same key.
Examples:
%w(a bb ccc).keyed_by(&:length) #=> {1 => 'a', 2 => 'bb', 3 => 'ccc'}
%w(a bb cc).keyed_by(&:length) #=> RuntimeError "duplicate key: 2"
14 15 16 17 18 19 20 21 22 |
# File 'lib/sublime_dsl/core_ext/enumerable.rb', line 14 def keyed_by h = {} each do |element| key = yield(element) h.key?(key) and raise "duplicate key: #{key.inspect}" h[key] = element end h end |