初学者的问题,请帮帮我
my_array = ["city1:state1","city2:state2","city3:state1","city4:state3","city5:state1"]
我如何从这个数组中生成这样的散列?
{
state1: [city1,city3,city5],
state2: [city2],
state3: [city4]
}
我正在尝试这种方式
my_hash = { }
my_array.each do |cs|
temp = cs.split(":")
if my_hash.keys.include? temp[1]
my_hash[temp[1]] = temp[0]
else
my_hash[temp[1]] = temp[0]
end
end
但我不知道如何匹配我的哈希键并附加到键。
最佳答案
稍微修改一下就可以了:
my_hash = { }
my_array.each do |cs|
temp = cs.split(":")
if my_hash.keys.include? temp[1].to_sym
my_hash[temp[1].to_sym] << temp[0]
else
my_hash[temp[1].to_sym] = [temp[0]]
end
end
结果是 {:state1=>["city1", "city3", "city5"], :state2=>["city2"], :state3=>["city4"]}
。我假设这就是您的意思(键是符号,值是字符串数组)。
关于ruby - 如何将多个值推送到同一个哈希键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26116192/