Project

better_dig

0.0
No commit activity in last 3 years
No release in over 3 years
Provide simple to use dig library for nested hash or array lookup
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
 Dependencies

Development

~> 1.16
~> 5.0
~> 10.0
 Project Readme

Gem Version Maintainability Test Coverage Build Status

BetterDig

Another kind of hash/array lookup you'll like

Supports dig-like method for Ruby below 2.3

Table of Context

  • Installation
  • Usage
  • Contributing
  • License

Installation

Add this line to your application's Gemfile:

gem 'better_dig'

And then execute:

$ bundle

Or install it yourself as:

$ gem install better_dig

Usage

Basic Examples

hash = { hello: 'world', nested: { hello: 'world' }, nested_array: ['hello', 'world'], is_cool: true }

# Fetch by digg
hash.digg(:hello)                #=> 'world'
hash.digg('hello')               #=> 'world'
hash.digg('nested', 'hello')     #=> 'world'
hash.digg('nested_array', 0)     #=> 'hello'
hash.digg('nested_array', '0')   #=> 'hello'
hash.digg(:hello, 0, :not_found) #=> nil

# Fetch by path
hash.fetch_path('nested/hello')                 #=> 'world'
hash.fetch_path('nested_array/0')               #=> 'hello'
hash.fetch_path('nested.hello', delimeter: '.') #=> 'hello'
hash.fetch_path('nested/hello/none', default: 'zh-tw.not_found') #=> 'zh-tw.not_found'
hash.fetch_path('is_cool') #=> true

# Since `nil` will be returned for not found value instead of TypeError if we are digging too far
# we can use conditional block without breaking the application

if hash.digg(:nested, :hello, :world) # => nil
  # DO SOMETHING WHEN FOUND
else
  # DO SOMETHING WHEN NOT FOUND
end

Or probably in the Rails views

<%= object.hash_data.digg(:snapshot, :price) %>

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/berniechiu/better_dig.

License

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