Cleanest way to create a Hash from an Array

前端 未结 5 1441
南方客
南方客 2021-02-01 15:56

I seem to run into this very often. I need to build a Hash from an array using an attribute of each object in the array as the key.

Lets say I need a hash of example us

相关标签:
5条回答
  • 2021-02-01 16:05

    Install the Ruby Facets Gem and use their Array.to_h.

    0 讨论(0)
  • 2021-02-01 16:13

    a shortest one?

    # 'Region' is a sample class here
    # you can put 'self.to_hash' method into any class you like 
    
    class Region < ActiveRecord::Base
      def self.to_hash
        Hash[*all.map{ |x| [x.id, x] }.flatten]
      end
    end
    
    0 讨论(0)
  • 2021-02-01 16:15

    There is already a method in ActiveSupport that does this.

    ['an array', 'of active record', 'objects'].index_by(&:id)
    

    And just for the record, here's the implementation:

    def index_by
      inject({}) do |accum, elem|
        accum[yield(elem)] = elem
        accum
      end
    end
    

    Which could have been refactored into (if you're desperate for one-liners):

    def index_by
      inject({}) {|hash, elem| hash.merge!(yield(elem) => elem) }
    end
    
    0 讨论(0)
  • 2021-02-01 16:20

    You can add to_hash to Array yourself.

    class Array
      def to_hash(&block)
        Hash[*self.map {|e| [block.call(e), e] }.flatten]
      end
    end
    
    ary = [collection of ActiveRecord objects]
    ary.to_hash do |element|
      element.id
    end
    
    0 讨论(0)
  • 2021-02-01 16:25

    In case someone got plain array

    arr = ["banana", "apple"]
    Hash[arr.map.with_index.to_a]
     => {"banana"=>0, "apple"=>1}
    
    0 讨论(0)
提交回复
热议问题