hash snippets

Stringify a Ruby Hash

Tagged stringify, hash, ruby, tokyo-cabinet  Languages ruby
class Hash
  def stringify
    inject({}) do |options, (key, value)|
      options[key.to_s] = value.to_s
      options
    end
  end

  def stringify!
    each do |key, value|
      delete(key)
      store(key.to_s, value.to_s)
    end
  end
end

Ruby Hash except and only

Tagged hash, ruby, except, only, reject  Languages ruby
class Hash
  def except(*blacklist)
    reject {|key, value| blacklist.include?(key) }
  end

  def only(*whitelist)
    reject {|key, value| !whitelist.include?(key) }
  end
end

How to use ActiveRecord::OrderedHash

Tagged ordered, hash, rails, activesupport  Languages ruby

Ruby 1.8 doesn't retain the order of objects inserted in to a hash, but with ActiveSupport::OrderedHash you can do this:

a=ActiveSupport::OrderedHash[:one, 1, :two, 2]

which gives you:

=> #<OrderedHash {:one=>1, :two=>2}>

Make a nested OpenStruct from a Hash in Ruby

Tagged ruby, nested, hash, ostruct  Languages ruby
class NestedOstruct < OpenStruct
  MAPPING = {
    Hash => ->(s) { new(s) },
    Array => ->(s) { s.collect { |i| i.is_a?(Hash) ? new(i) : i } }
  }.freeze

  def initialize(hash)
    super
    hash.each do |k, v|
      self[k] = (MAPPING[v.class] || ->(s) { s })[v]
    end
  end

  def method_missing(meth, *args)
    raise NoMethodError, meth unless meth.to_s.end_with?('=')

    super
  end

  def respond_to_missing?(_method_name, _include_private = false)
    super
  end
end

There’s also the Hashie gem https://github.com/hashie/hashie, but some people consider it “harmful”: https://www.schneems.com/2014/12/15/hashie-considered-harmful.html