When there was a nesting structure of hash in ruby (like the value of hash has hash again), I wanted to specify elements in xml as xpath.For example, if you want to delete an element,
h={name:
{"Japanese_first_name"=>"Taro",
"Japanese_last_name" = > "Tanaka",
"English_first" = > "Taro",
"English_last" = > "Tanaka"
},
age —18
}
del(h, [:name, /Japanese /])
# =>{:name=>{"english_first"=>"Taro", "english_last"=>"Tanaka"},:age=>18}
It would be nice to have a method like , where del
represents the path of hash to compare with case
(or rather ===
).
When I tried implementing this del, it looked like this.
def del(h,xpath_ish)
return h.reject { | k , v | xpath_ish.first === k } if xpath_ish.size == 1
h.map do|k,v|
new_v=xpath_ish.first===k?del(v,xpath_ish.drop(1)):v
[k, new_v]
end.to_h
end
Now that you've written and defined del, you'd like to define map, redundancy, etc. as well.
However, I thought that if you use ruby, you might want to do it relatively well, so I thought that some existing libraries would do this.
© 2024 OneMinuteCode. All rights reserved.