Created
November 12, 2011 17:00
-
-
Save takeshy/1360813 to your computer and use it in GitHub Desktop.
hashの値の比較にsymbolでも文字列でも同値とする
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
[email protected] && 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