Another kind of hash/array lookup you'll like
Supports dig-like method for Ruby below 2.3
Add this line to your application's Gemfile:
gem 'better_dig'
And then execute:
$ bundle
Or install it yourself as:
$ gem install better_dig
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) %>
Bug reports and pull requests are welcome on GitHub at https://github.com/berniechiu/better_dig.
The gem is available as open source under the terms of the MIT License.