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

Pigeonhole principle

Tagged crc, cryptography, hash, md5, sha256  Languages 

When working with hashing functions and cryptography the pigeonhole principle is essential knowledge: https://en.wikipedia.org/wiki/Pigeonhole_principle

In mathematics, the pigeonhole principle states that if n items are put into m containers, with n > m, then at least one container must contain more than one item.

For example, given that the population of London is greater than the maximum number of hairs that can be present on a human’s head, then the pigeonhole principle requires that there must be at least two people in London who have the same number of hairs on their heads.

This means that in order to create a completely collision-free hashing function, every message would have to have a hashed output of the same length as the input.