Ruby 1.9 regex as a hash key

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

    Are you looking for this behaviour?

    myhash = Hash.new{|h,k| h[k] = 'hello' if k =~ /(\d+)/}
    
    p myhash['aaa'] #=> nil
    p myhash #=> {}
    p myhash['1234'] #=>" hello"
    p myhash #=> {"1234"=>"hello"}
    

提交回复
热议问题