2011-12-30 2 views
2

내가에서이 예제를 다음있어 실행 한 후"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!
감사합니다 모두

+0

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

+0

예 원래 책이 말한 것을 시도했지만 위의 오류가 발생했습니다. (내 업데이트 된 게시물 참조). 그때 나는 내 길을 시험해 보았다. 그리고 내가 봤던 오류 메시지를 받았다. 어쨌든 해시를 작성하는 다른 방법을 이용해 주셔서 감사합니다. 그것은 컴파일하지만, http : // localhost : 4567/throw/scissors 페이지를 방문하면 NoMethodError를 얻는 것처럼 보입니다. – mpdunson

+0

전체 오류는 무엇인가요? 해시 구문과 관련이 없을 수 있습니다. –

답변

2

나는 그들이 @defeat = { rock: :scissors, paper: :rock, scissors: :paper }을 의미 믿습니다. 이제 새로운 스타일의 Ruby 해시를 사용합니다.이 해시는 { :rock => :scissors, :paper => :rock, :scissors => :paper }과 같이 작성 될 수도 있습니다.

0

오류는 어디에 문제가 있는지 설명합니다. 당신이 IRB에 @defeat에 대한 정의를 붙여 넣을 경우 :

1.9.2p290 :002 > @defeat = {rock :scissors, paper :rock, scissors :paper} 
SyntaxError: (irb):2: syntax error, unexpected tSYMBEG, expecting keyword_do or '{' or '(' 
@defeat = {rock :scissors, paper :rock, scissors :paper} 
       ^

당신은 @sczizzo에 의해 주어진 답을 수행하여 문제를 해결할 수 있습니다.

+0

Frederich Cheung이 Ruby 1.9 버전을 가지고 있지 않다는 것을 알았습니다. 그것이 문제였습니다. 이러한 해시 작업은 1.9에서만 지원됩니다. 나는 1.8의 동등 물이있다라고 확신한다. 그러나 1.9는 트릭을했다. – mpdunson

+0

1.8 등가물이 없다고 생각합니다. '=>'연산자의 사용은 내가 옳은 것을 기억한다면 하드 와이어되어있다. 1.8.7에서는 "[백 포트] (http://rubydoc.info/gems/backports/frames)"젬을 사용하여'Array.sample'을 얻을 수 있습니다. –

관련 문제