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}>