Ruby 1.9 regex as a hash key

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

    It will not work without some extra code, as it is you are comparing a Regexp object with either an Integer or a String object. They won't be value equal, nor identity equal. They would match but that requires changes to the Hash class code.

    irb(main):001:0> /(\d+)/.class
    => Regexp
    irb(main):002:0> 2222.class
    => Fixnum
    irb(main):003:0> '2222'.class
    => String
    irb(main):004:0> /(\d+)/==2222
    => false
    irb(main):007:0> /(\d+)/=='2222'
    => false
    irb(main):009:0> /(\d+)/.equal?'2222'
    => false
    irb(main):010:0> /(\d+)/.equal?2222
    => false
    

    you would have to iterate the hash and use =~ in something like:

     hash.each do |k,v|    
       unless (k=~whatever.to_s).nil?
         puts v   
       end
     end
    

    or change the Hash class to try =~ in addition to the normal matching conditions. (I think that last option would be difficult, in mri the Hash class seems to have a lot of C code)

提交回复
热议问题