gpt4 book ai didi

ruby - 为什么我会收到 "Sinatra: Up and Running"game.rb "Rock Paper Scissors"的语法错误?

转载 作者:太空宇宙 更新时间:2023-11-03 16:08:38 25 4
gpt4 key购买 nike

我正在按照“Sinatra:启动并运行”中的这个示例进行操作,但收到以下错误消息:

game.rb:8: odd number list for Hash
    @defeat = { rock:  :scissors, paper:  :rock, scissors:  :paper }
                                ^
game.rb:8: syntax error, unexpected ':', expecting '}'
    @defeat = { rock:  :scissors, paper:  :rock, scissors:  :paper }
                                ^

运行后:

$ ruby -rubygems game.rb

但是,我不知道为什么这个语句有问题。我直接从书上复制了代码。我尝试了很多变体,但似乎没有任何效果。这段代码假设输出“Ouch rock beats scissors. Better luck next time!”如果我转到 localhost:4567/throw/scissors 并且计算机选择了 rock。

下面的game.rb

require 'sinatra'

# before we process a route, we'll set the response as
# plain text and set up an array of viable moves that
# a player (and the computer) can perform
before do
content_type :txt
@defeat = {rock: :scissors, paper: :rock, scissors: :paper}
@throws = @defeat.keys
end

get '/throw/:type' do
# the params[] hash stores querystring and form data.
player_throw = params[:type].to_sym

# in the case of a player providing a throw that is not valid,
# we halt with a status code of 403 (Forbidden) and let them
# know they need to make a valid throw to play.
if !@throws.include?(player_throw)
halt 403, "You must throw one of the following: #{@throws}"
end

# now we can select a random throw for the computer
computer_throw = @throws.sample

# compare the player and computer throws to determine a winner
if player_throw == computer_throw
"You tied with the computer. Try again!"
elsif computer_throw == @defeat[player_throw]
"Nicely done; #{player_throw} beats #{computer_throw}!"
else
"Ouch; #{computer_throw} beats #{player_throw}. Better luck next time!"
end
end

顺便说一句,我用于原始问题的代码实际上是我尝试的“修复”之一,而不是实际的书籍代码。显然,书籍代码与 sczizzo 建议的内容相同。但是,我仍然遇到错误(见上文)。不管怎样,如果我尝试 sczizzo 替代品:

{  :rock  => :scissors, :paper => :rock, :scissors => :paper  }

然后 game.rb 编译,但出现运行时错误:

#<NoMethodError: undefined method `sample' for [:rock, :scissors, :paper]:Array>

如果我访问 http://localhost:4567/throw/scissors

解决方案:安装 Ruby 1.9!
谢谢大家

最佳答案

我相信他们的意思是 @defeat = { rock: :scissors, paper: :rock, scissors: :paper }。现在,它使用了一种新型的 Ruby 哈希,它也可以这样写:{ :rock => :scissors, :paper => :rock, :scissors => :paper }.

关于ruby - 为什么我会收到 "Sinatra: Up and Running"game.rb "Rock Paper Scissors"的语法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8675024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com