【发布时间】:2021-05-17 02:01:14
【问题描述】:
我需要在哈希中找到一个键,然后如果该键已经存在则返回 true,如果不存在则返回 false,但由于某种原因我在终端中出现错误。 这是我的方法:
def key_no_exist (hash,key)
hash.each do |clave,valor|
if clave == key
return false
end
end
return true
结束
在我在这段代码中使用返回之后:
when "set"
key = sep[1] #string who contain my key
client.puts "SEND DATABLOCK: "
resp = client.gets.chomp
datablock = resp.scan(/\w+/)
if key_no_exist(data,key) #if the key doesn't exist, add the data block into the hash
data[:key] = datablock
client.puts"STORED: \r\n "
else
client.puts "CLIENT_ERROR [key already exists]\r\n"
end
毕竟当我在终端中运行代码时,我遇到了这个问题: :22: 警告:已分配但未使用的变量 - 数据
:75: 警告:方法名称后的括号被解释为参数列表,而不是分解的参数
在block (2 levels) in run':undefined local variable or method data' 中为#Server:0x00007fdd0695d8d8 (NameError)
首先我创建一个名为 data 的哈希:
class Server
def initialize(port,ip)
@server = TCPServer.open(ip,port)
@connections = Hash.new
@clients = Hash.new
@connections[:server] = @server
@connections[:clients] = @clients
data = Hash.new
run
end
【问题讨论】:
-
为什么不直接使用
has_key?