Skip to content

Instantly share code, notes, and snippets.

@stefansundin
Created May 25, 2015 06:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefansundin/ab871e91c9b46c465fb8 to your computer and use it in GitHub Desktop.
Save stefansundin/ab871e91c9b46c465fb8 to your computer and use it in GitHub Desktop.
Ruby stringified hash.
# I have been annoyed that hash[:key] != hash["key"], which has caused problems more than once when converting things to Sidekiq jobs, etc.
# This is a major hack, and it is probably not really useful unless you can monkey patch the Hash class, which I didn't succeed with.
# I will have to look into how Rack does the params magic...
class StringHash < Hash
def []=(key, val)
super(key.to_s, val)
end
def [](key)
super(key.to_s)
end
def has_key?(key)
super(key.to_s)
end
def merge(other_hash)
new_hash = self.clone
other_hash.each do |k,v|
new_hash[k] = v
end
new_hash
end
def merge!(other_hash)
other_hash.each do |k,v|
self[k] = v
end
self
end
def values_at(*keys)
super(*keys.map(&:to_s))
end
alias_method :include?, :has_key?
alias_method :key?, :has_key?
alias_method :member?, :has_key?
alias_method :store, :[]=
alias_method :update, :merge!
end
h = StringHash.new
h[:test] = "arnold"
h["test"] == h[:test] # => true
h.any? { |k,v| k == :test } # => false
h.merge!({kossa: 'muu'})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment