在redy hash中使用正则表达式作为关键字

Bru*_*Lin 3 ruby regex hash

我有哈希映射

H = {
    "alc" => "AL",
    "alco" => "AL",
    "alcoh" => "AL",
    "alcohol" => "AL",
    "alcoholic" => "AL",
}
Run Code Online (Sandbox Code Playgroud)

现在我想使用正则表达式来表示所有键,例如H = {/ ^ alc/=>"AL"}

后来我想使用H ["alc"]或H ["alco"]来检索值.但是,如果我使用正则表达式,我无法正确获得该值.我该怎么办?

Kas*_*sel 6

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)

我会创建哈希的子类,然后重写这个方法.这样,您仍然可以将常规哈希功能保留在其他位置.


And*_*ros 5

创建一个子类,继承Hash类并覆盖[]行为,以便检查它是否与哈希中的每个正则表达式匹配并返回相应的值.