私は「シナトラ:Upと実行」から、この例を次のようだ、と私は、次のエラーメッセージが出ます:しかし、私はなぜそれ見当がつかない"Sinatra:Up and Running" game.rb "Rock Paper Scissors"で構文エラーが発生するのはなぜですか?
$ ruby -rubygems game.rb
:実行後
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 }
^
をこの声明には問題があります。私はその本から直接コードをコピーしました。私は多くのバリエーションを試しましたが、何も動作していないようです。このコードでは、 "Ouch rock beats scissors。次回はより良い運があります!"と出力されます。私がlocalhost:4567/throw/scissorsに行くと、コンピュータはロックを選択します。
私は元の質問のために使用されるコードは、実際に私は、実際の本のコードではありません試してみました「修正」の一つであったところで
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 [email protected]?(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
以下game.rb。どうやら本のコードはsczizzoが提案したのと同じものだったようです。しかし、私はまだエラーが発生しています(上記参照)。 game.rbコンパイル、その後
{ :rock => :scissors, :paper => :rock, :scissors => :paper }
、私はランタイムエラーを取得:私はsczizzo代替を試してみてくださいとにかく場合INSTAL:私はhttp://localhost:4567/throw/scissors
ソリューションを訪れる場合
#<NoMethodError: undefined method `sample' for [:rock, :scissors, :paper]:Array>
をRuby 1.9!私は、彼らが@defeat = { rock: :scissors, paper: :rock, scissors: :paper }
を意味信じる
おかげでみんな
[Googleブックスで探しているページ](http://books.google.com/books?id=0aF5-u3H9SQC&pg=PA12&lpg=PA12&dq=Sinatra:+Up+and+Running+game)が見つかりました。私の答えを確認するrb&source = bl&ots = gqAgp5jELe&sig = mrnFcTYICniG5823NdjIpVq8KbA&hl = en&sa = X&ei = tg79TuPhL4SKgwe26ZWsAg&ved = 0CCUQ6AEwAQ#v = onepage&q&f = false)おそらくあなたの版に誤植があるかもしれません。 – sczizzo
はい私はもともと本が言ったことを試してみました。私は上記のエラーを受けました。 (私の最新の記事を見てください)。それから私は自分のやり方を試みました。あなたが私が見たエラーメッセージが出ました。とにかく、ハッシュを書く代わりの方法に感謝します。それはコンパイルされますが、http:// localhost:4567/throw/scissorsというページにアクセスすると、NoMethodErrorが発生するようです。 – mpdunson
完全なエラーは何ですか?ハッシュ構文とは無関係かもしれません。 –