问题描述
我正在尝试这个例子 myhash = {/(\ d +)/ => hello}
with ruby 1.9.2p136(2010-12-25)[i386-mingw32] 。
它没有像预期的那样工作(编辑:因为事实证明它不应该像我期待的那样工作):
irb (主):004:0> myhash = {/(\ d +)/ => hello}
=> {/(\ d +)/ =>Hello}
irb(main):005:0> myhash [2222]
=>无
irb(main):006:0> myhash [2222]
=> nil
在,这是ruby1.8.7 的作品。
我是什么失踪?
如果没有额外的代码,它将无法正常工作,因为它是将Regexp对象与Integer或String目的。他们不会是价值平等,也不是身份平等。它们会匹配,但需要对Hash类代码进行更改。
irb(main):001:0> /(\d+)/.class
=>正则表达式
irb(main):002:0> 2222.class
=> Fixnum
irb(main):003:0> '2222'.class
=>字符串
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
您必须迭代哈希并使用=〜如下所示:
hash.each do | k,v |
除非(k =〜whatever.to_s).nil?
puts v
end
end
或更改Hash类尝试=〜除了正常的匹配条件。 (我认为最后一个选项会很困难,在Hash类中,似乎有很多C代码)。
I am trying this example myhash = {/(\d+)/ => "hello"}
with ruby 1.9.2p136 (2010-12-25) [i386-mingw32].
It doesn't work as expected (edit: as it turned out it shouldn't work as I was expecting):
irb(main):004:0> myhash = {/(\d+)/ => "hello"}
=> {/(\d+)/=>"Hello"}
irb(main):005:0> myhash[2222]
=> nil
irb(main):006:0> myhash["2222"]
=> nil
In Rubular which is on ruby1.8.7 the regex works.
What am I missing?
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)
这篇关于Ruby 1.9正则表达式作为散列键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!