Quantcast
Channel: Active questions tagged ruby - Stack Overflow
Viewing all articles
Browse latest Browse all 4623

Ruby library function to transform Enumerable to Hash

$
0
0

Consider this extension to Enumerable:

module Enumerable  def hash_on    h = {}    each do |e|      h[yield(e)] = e    end    h  endend

It is used like so:

people = [  {:name=>'fred', :age=>32},  {:name=>'barney', :age=>42},]people_hash = people.hash_on { |person| person[:name] }p people_hash['fred']      # => {:age=>32, :name=>"fred"}p people_hash['barney']    # => {:age=>42, :name=>"barney"}

Is there a built-in function which already does this, or close enough to it that this extension is not needed?


Viewing all articles
Browse latest Browse all 4623

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>