Ruby 1.9 regex as a hash key

前端 未结 5 1141
南笙
南笙 2021-02-13 13:39

I am trying this example myhash = {/(\\d+)/ => \"hello\"} with ruby 1.9.2p136 (2010-12-25) [i386-mingw32].
It doesn\'t work as exp

5条回答
  •  悲哀的现实
    2021-02-13 14:27

    You can put Jean's answer in a default_proc

    MAP = {
      /1/ => "one",
      /2/ => "two",
      /\d/ => "number"
    }
    
    MAP.default_proc = lambda do |hash, lookup|
      hash.each_pair do |key, value|
        return value if key =~ lookup
      end
      return nil
    end
    
    p MAP["2"] #=> "two"
    p MAP[44] #=> "number"
    

提交回复
热议问题