내가에서이 예제를 다음있어 실행 한 후"Sinatra : Up and Running"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 }
^
을 :
$ ruby -rubygems game.rb
을 그러나, 나는 아무 생각 왜이 없다 이 성명서에 문제가있다. 책에서 바로 코드를 복사했습니다. 여러 변형을 시도했지만 아무 것도 작동하지 않는 것 같습니다. 이 코드는 "Ouch rock beats 가위를 출력합니다. 다음 번에 더 나은 행운을!" 내가 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 대안을 시도 어쨌든 만약 내가 http://localhost:4567/throw/scissors
솔루션을 방문하는 경우
#<NoMethodError: undefined method `sample' for [:rock, :scissors, :paper]:Array>
을 : 설치된의를 루비 1.9!
감사합니다 모두
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
전체 오류는 무엇인가요? 해시 구문과 관련이 없을 수 있습니다. –