0

我有一个看起来像的红宝石哈希

{"10.1.1.6"=>"nick", "127.0.0.1"=>"nick1"}

但是我无法检查某个字符串是否已经在哈希中。我试过了,使用thenhas_value?获取值数组来检查它是否包含它,但是当我知道它存在时总是返回。例如,我尝试添加到哈希中,我这样做:valuesinclude?false"172.16.10.252"=>"nick"

class SomeClass
  def initialize(*args)
    super(*args)
    @nicks = Hash.new
  end

  def serve(io)
    loop do
      line = io.readline
      ip = io.peeraddr[3]
      begin
        if  /NICK (.*)/ =~ line
          nick = $1
          if @nicks.has_value?(nick) # it fails here
            puts "New nick #{$1}"
            @nicks[ip] = nick.gsub("\r", "")
            io.puts "Your new nick is #{nick}"
          else
            message = {:ERROR => "100", :INFO=>"#{nick}"}.to_json
            io.puts message
          end
        end
      rescue Exception => e
        puts "Exception! #{e}-#{e.backtrace}"
      end
    end
  end
end

irb它上面工作正常,但在我的脚本上它没有

1.9.3p125 :001 > h = {"10.1.1.6"=>"nick", "127.0.0.1"=>"nick1"}
 => {"10.1.1.6"=>"nick", "127.0.0.1"=>"nick1"} 
1.9.3p125 :002 > h.has_value?('nick')
 => true 
1.9.3p125 :003 > if h.has_value?('nick')
1.9.3p125 :004?>   puts "yes"
1.9.3p125 :005?>   else
1.9.3p125 :006 >     puts "no"
1.9.3p125 :007?>   end
yes
 => nil 
1.9.3p125 :008 > 

我做错了什么?

4

2 回答 2

2

我不确定您是否按照您的意图使用“$1”。

在此行的代码中:

if  /NICK (.*)/ =~ line
  nick = $1
  if @nicks.has_value?(nick) # it fails here
        puts "New nick #{$1}"

if line is "NICK says a bunch of things", $1 will be "says a bunch of things". So you're not really looking for the value 'nick' in your hash, but for 'says a bunch of things'.

于 2012-04-08T14:55:44.710 回答
0

你应该检查你的正则表达式是如何工作的,我不会说哈希有什么问题。

于 2012-04-08T10:50:30.087 回答