[Awesome Ruby Gem] Use hashie gem to extend Hashes and make them more useful

hashie

Hashie is a growing collection of tools that extend Ruby Hashes and make them more useful.

This article is about how to use Hashie::Mash to access hash value with symbol key or dynamic method.

Visit hashie/hashie: Hashie is a collection of classes and mixins that make Ruby hashes more powerful. - https://github.com/hashie/hashie#mash
to learn more examples.

Installation

You can install it as a gem:

1
$ gem install hashie

or add it into a Gemfile (Bundler):

1
2
3
4
5
# Gemfile

# hashie/hashie: Hashie is a collection of classes and mixins that make Ruby hashes more powerful.
# https://github.com/hashie/hashie
gem 'hashie', `4.1.0'

Then, run bundle install.

1
$ bundle install

Usage

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
> json = JSON.parse('{"foo": 1}')
=> {"foo"=>1}

> json["foo"]
=> 1

# Can't access with symbol key.
> json[:foo]
=> nil

# Can't access with dynamic method.
> json.foo
Traceback (most recent call last):
1: from (irb):23:in `<main>'
NoMethodError (undefined method `foo' for {"foo"=>1}:Hash)

Use Hashie::Mash to access hash value with symbol or dynamic method.

1
2
3
4
5
6
7
8
9
10
11
12
13
> mash = Hashie::Mash.new(JSON.parse('{"foo": 1}'))
=> #<Hashie::Mash foo=1>

> mash["foo"]
=> 1

# Access with symbol key.
> mash[:foo]
=> 1

# Access with dynamic method.
> mash.foo
=> 1

References

[1] hashie/hashie: Hashie is a collection of classes and mixins that make Ruby hashes more powerful. - https://github.com/hashie/hashie#mash

[2] hashie | RubyGems.org | your community gem host - https://rubygems.org/gems/hashie/