I need to change the key names of a hash to numbered names. Eg
hash = {"0"=>["val", "val"], "1"=>["val"], "6"=>["val", "val"], "7"=>["val"]}
into
hash = {"0"=>["val", "val"], "1"=>["val"], "2"=>["val", "val"], "3"=>["val"]}
The numbering will start at zero and continue until the end of the hash. The hash length will be random.
new_hash = hash.values.map.with_index { |value, idx| [idx.to_s, value] }.to_h
#=> {"0"=>["val", "val"], "1"=>["val"], "2"=>["val", "val"], "3"=>["val"]}
key = -1
Hash[hash.map { |_,v| [(key = key.next).to_s, v] }]
or
hash.map { |_,v| [(key = key.next).to_s, v] }.to_h
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.