Create a gist now

Instantly share code, notes, and snippets.

hashの値の比較にsymbolでも文字列でも同値とする
require 'forwardable'
class HashWithValueIndifferentAccess
extend Forwardable
attr_accessor :hash
def_delegators(:@hash,*({}.public_methods - Object.new.public_methods - ["[]","[]=","values","==","to_s"]))
def initialize(hash={})
@hash={}
hash.each do|k,v|
if v.is_a?(Symbol)
@hash[k] = v.to_s
else
@hash[k] = v
end
end
end
def values
@hash.values.map{|v| v.is_a?(String) ? SymboledString.new(v) : v}
end
def [](key)
if @hash[key].is_a?(String)
SymboledString.new(@hash[key])
else
@hash[key]
end
end
def []=(key,val)
if val.is_a?(Symbol)
@hash[key] = val.to_s
else
@hash[key] = val
end
end
def ==(vals)
vals.keys==@hash.keys && values == @hash.values
end
def to_s
@hash.to_s
end
end
class SymboledString < String
def ==(val)
if val.is_a?(Symbol)
val.to_s == self
else
val == self
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment