我有一些数据以['a1', 'b321', 'a33', 'c', ...]
的形式排列为数组。 我想把所有的'aN'放入sorted_data[:a]
等。 下面的代码循环遍历数据,并正确地在它们上运行正则表达式。 它没有做的是把它们放在正确的地方 - sorted_data[filter[:key]]
为空。 如何使用filter[:key]
作为sorted_data
的关键? 谢谢。在哈希中使用变量作为另一个哈希的关键
sorted_data = { a: Array.new,
b: Array.new,
c: -1 }
filters = [{ re: /^a\d+$/, key: 'a' },
{ re: /^b\d+$/, key: 'b' },
{ re: /^c$/, key: 'c' }]
['a1', 'b321', 'a33', 'c', 'b', 'b1'].each {|cell|
filters.each {|filter|
if cell.match(filter[:re])
puts "#{cell} should go in #{filter[:key]}" + '....[' + sorted_data[filter[:key]].to_s + ']....'
break
end
}
}
的上述输出是
# a1 should go in a....[]....
# b321 should go in b....[]....
# a33 should go in a....[]....
# c should go in c....[]....
# b1 should go in b....[]....
也许是因为':一个!='a''? – 2014-09-19 11:00:28
你能更有帮助吗? – gotofritz 2014-09-19 11:17:43
'sorted_data'具有符号键(':a,:b,:c'),'filters'将键定义为字符串('“a”,“b”,“c”') – 2014-09-19 16:36:07