aelor
aelor

Reputation: 11116

convert ruby hash into another format

here is a ruby hash

hash = {"ss"=>1, "bc/gf"=>"120/22", "bb"=>"hh"}

I want to convert it to

{"ss"=>1, "bc"=>"120", "gf" => "22", "bb"=>"hh"}

what I tried

key_arr = has.keys.map{|s| s.split("/")}.flatten
val_arr = has.values.map(&:to_s).map{|s| s.split("/")}.flatten
Hash[*key_arr.zip(val_arr).flatten]

works fine for me .. but is there a more elegant solution to my problem

Upvotes: 0

Views: 144

Answers (2)

falsetru
falsetru

Reputation: 368894

Using Enumerable#each_with_object:

hash = {"ss"=>1, "bc/gf"=>"120/22", "bb"=>"hh"}
hash.each_with_object({}) { |(key, value), h|
  value = value.to_s
  key.split('/').zip(value.split('/')) { |k, v|
    h[k] = v
  }
}
# {"ss"=>"1", "bc"=>"120", "gf"=>"22", "bb"=>"hh"}

Upvotes: 2

pierallard
pierallard

Reputation: 3371

hash = {"ss"=>1, "bb/gf"=>"120/22", "bb"=>"hh"}
hash2 = hash.inject({}) do |h, (key, value)|
  h.merge([ key.to_s.split('/'), value.to_s.split('/')].transpose.to_h)
end

Upvotes: 0

Related Questions