LoginSignup
2
2

More than 5 years have passed since last update.

Mash: Make hash from Enumerable

Last updated at Posted at 2013-08-11

People used to do it this way:

hash = {}
input.each do |item|
  hash[item] = process(item)
end
hash

: (

Two solutions:

# from http://www.h6.dion.ne.jp/~machan/misc/FPwithRuby.html
module Enumerable
  def mash(&block)
    self.inject({}) do |output, item|
      key, value = block_given? ? yield(item) : item
      output.merge(key => value)
    end
  end
end

module Enumerable
  def mash(&block)
    Hash[self.map do |item|
      if block_given?
        yield(item)
      else
        nil
      end
    end]
  end
end

syntax

pry > ["I", "love", "Ruby"].mash { |w| [w, w.size] }
=> {"I"=>1, "love"=>4, "Ruby"=>4}

Which one do you prefer?

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2