ruby - using an alias name for hash key value -
i have json data receive , json.parse
hash. hash key names integer strings data["0"]
, data["1"]
, data["2"]
, etc... each value correspond state. 0 => start, 1 => stop, 2 => restart.
i can't change source json data make key more readable. each hash have 5 pairs correspond 5 different states.
i wondering if there nice way me alias numbers meaningful names when referencing hash key value don't have use number.
at moment i'm using constants below, thinking there might nicer, more ruby way. use hash or struct can use data[states.start]
or something?
state_start = "0" state_stop = "1" state_restart = "2" data = json.parse value puts data[state_start]
thanks
i think constants fine. if want rubify code bit, can, example, wrap source hash in object translate method names.
class myhash def initialize(hash) @hash = hash end mapping = { start: '0', stop: '1', restart: '2', } # dynamically define methods # # def start # @hash['0'] # end # # or can use method_missing mapping.each |method_name, hash_key| define_method method_name @hash[hash_key] end end end mh = myhash.new({'0' => 'foo', '1' => 'bar'}) mh.start # => "foo" mh.stop # => "bar"
Comments
Post a Comment