我有哈希映射
H = {
"alc" => "AL",
"alco" => "AL",
"alcoh" => "AL",
"alcohol" => "AL",
"alcoholic" => "AL",
}
Run Code Online (Sandbox Code Playgroud)
现在我想使用正则表达式来表示所有键,例如H = {/ ^ alc/=>"AL"}
后来我想使用H ["alc"]或H ["alco"]来检索值.但是,如果我使用正则表达式,我无法正确获得该值.我该怎么办?
class MyHash < Hash
def [](a)
self.select {|k| k =~ a}.shift[1]
end
end
result = MyHash.new
result[/^alc/] = "AL"
puts result['alcohol'] #=> 'AL'
Run Code Online (Sandbox Code Playgroud)
我会创建哈希的子类,然后重写这个方法.这样,您仍然可以将常规哈希功能保留在其他位置.