Project

map_h

0.0
No commit activity in last 3 years
No release in over 3 years
Enumerable#map_h creates a hash using each element of the Enumerable.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies

Development

>= 0
~> 13.0
 Project Readme

map_h

Adds a map_h method to Enumerable for easily building hashes from a given block.

Gem Version Build Status

This is similar to the existing map method, but retains the original values as the keys in the resulting hash.

Installation

Add this line to your application’s Gemfile:

gem 'map_h'

And then execute:

$ bundle

Usage

The method will be added to all Enumerable objects when you:

require 'map_h'

To use map_h, pass it a block. For example:

['john', 'paul', 'george', 'ringo'].map_h { |name| name.length }
# => {'john' => 4, 'paul' => 4, 'george' => 6, 'ringo' => 5}

Or you can use the shorthand Symbol#to_proc syntax:

['john', 'paul', 'george', 'ringo'].map_h(&:length)
# => {'john' => 4, 'paul' => 4, 'george' => 6, 'ringo' => 5}

If the Enumerable yields multiple values (e.g. Hash), an array of these values will be used as the key:

{
  'george' => 'guitar',
  'ringo'  => 'drums'
}.map_h {|name, instrument| "#{instrument}: #{name}"}
# => {
#      ['george', 'guitar'] => "guitar: george",
#      ['ringo', 'drums']   => "drums: ringo"
#    }

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/fishpercolator/map_h. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Future

  • Have map_h return an Enumerator instead of raising an exception if no block is passed.