Ruby 1.9 regex as a hash key

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

    It never occurred to me to use a regex as a hash key. I'm honestly not sure if that should work, nor exactly how it would work if it should.

    In any case, two thoughts:

    1. In your attempts to lookup the item, you use hash, but the hash is named myhash.
    2. If I play around with it, I get these results:

      hektor ~ ❯❯ irb
      >> myhash = {/(\d+)/ => "hello"}
      => {/(\d+)/=>"hello"} 
      >> myhash['2222']
      => nil 
      >> myhash[2222]
      => nil 
      >> myhash[/(\d+)/]
      => "hello" 
      

    This is using Ruby 1.9.2-p180.

    Ok, checked and here's what works:

    myhash = {/foo/ => "hello"}
    myhash[/foo/] # => "hello"
    

    The lookup is on the key, and the key is a regex, not one of the many potential matches of that regex.

提交回复
热议问题