Tash is a hash that allows for transformation of its keys. A transformation block is given to change the key. Keys can be looked up with any value that transforms into the same key. This means a hash can be string/symbol insensitive, case insensitive, can convert camel case JSON keys to snake case Ruby keys, or anything else based on the block you provide.
Add it to your Gemfile:
gem 'tash', '~> 1.0'
Or install it manually:
$ gem install tash --version '~> 1.0'
This project uses Semantic Versioning. Check out GitHub releases for a detailed list of changes.
Let's say that you wanted to have a hash where the keys are accessible as strings or symbols (i.e. ActiveSupport::HashWithIndifferentAccess
).
t = Tash[one: 1, two: 2, &:to_s]
# => {"one"=>1, "two"=>2}
t[:one]
# => 1
t['one']
# => 1
t[:three] = 9 # oops
# => 9
t['three'] = 3
# => 3
t[:three]
# => 3
t['three']
# => 3
Lets say that you recieve a series of camel case JSON keys from an API call but want to access the information with Rubys typical snake case style and symbolized.
json = { "firstName" => "Adam", "lastName" => "DeCobray" }
t = Tash[json] do |key|
key
.to_s
.gsub(/(?<!\A)([A-Z])/, '_\1')
.downcase
.to_sym
end
t[:first_name]
# => "Adam"
t['firstName']
# => "Adam"
This also works with pattern matching:
t = Tash[ONE: 1, MORE: 200, &:downcase]
case t
in { One: 1, More: more }
more
else
nil
end
# => 200
Tash implements to_hash
for implicit hash conversion making it usable nearly everywhere you use a hash.
Tash has every instance method Hash has except for transform_keys
and transform_keys!
.
If you want to contribute to Tash, please read our contribution guidelines. A complete list of contributors is available on GitHub.
Tash is licensed under the MIT License.