Ruby 1.9 regex as a hash key

前端 未结 5 1146
南笙
南笙 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:21

    There is now a gem called Hashie that provides this feature (and much more): https://github.com/intridea/hashie#rash

    It provides a data structure called Rash (short for regex-hash) that can be used like this

    myhash = {/(\d+)/ => "hello"}
    rash = Hashie::Rash.new(myhash)
    
    >> rash["2222"]
    => "hello"
    

    It really tries to match the key against the regexes so numeric keys won't work unless you convert them to string, which you can do easily by inheriting Rash into your own class

提交回复
热议问题