没有将Hash隐式转换为String(Ruby)

时间:2018-04-19 08:19:57

标签: ruby

如果有人输入"!disconnect",我希望机器人使用响应"PART ##{CHANNEL}"断开连接。

下面的代码段不是完整代码,但有end个语句和所有内容。

CHANNEL = "SomeChannelHere"
prefix = "!"
message = "!disconnect"

commands = [
    "disconnect" => "PART ##{CHANNEL}"]

commands.each do |command|
    if message.include?(prefix + command)
        response = commands[command]

我如何得到回复?

2 个答案:

答案 0 :(得分:2)

您的commands目前是一系列哈希:

commands = ["disconnect" => "PART ##{CHANNEL}"]
#=> [{"disconnect"=>"PART #SomeChannelHere"}]

您必须使用{ ... }代替[ ... ]

commands = {"disconnect" => "PART ##{CHANNEL}"}
#=> {"disconnect"=>"PART #SomeChannelHere"}

此外,each块需要两个参数(键和值):

commands.each do |command, response|
  # ...
end

答案 1 :(得分:0)

你错过了哈希的关键:

commands.each do |command|
 p command["disconnect"]
 p command.has_key?("disconnect")
end