2013-10-15 19 views
0

從這個例子逐字輸入代碼,並接收以下語法錯誤消息。請幫忙!!Noob和谷歌搜索代碼接收語法錯誤

https://github.com/visionmedia/google-search/blob/master/examples/web.rb

我的代碼:

require "rubygems" 
require "google-search" 

def find_item uri, query 
    search = Google::Search::Web.new do |search| 
     search.query = query 
     search.size = :large 
     search.each_response {print "."; #stdout.flush} 
    end 
     search.find {|item| item.uri =~ uri} 
end 

def rank_for query 
    print "%35s " % query 
    if item = find_item(/vision\-media\.ca/, query) 
     puts " #%d" % (item.index +1) 
    else 
     puts " Not found" 
    end 
end 

rank_for "Victoria Web Training" 
rank_for "Victoria Web School" 
rank_for "Victoria Web Design" 
rank_for "Victoria Drupal" 
rank_for "Victoria Drupal Development" 

錯誤消息:

Ruby Google Search:9: syntax error, unexpected keyword_end, expecting '}' 
Ruby Google Search:11: syntax error, unexpected keyword_end, expecting '}' 
Ruby Google Search:26: syntax error, unexpected $end, expecting '}' 

回答

2

你無意中註釋掉線9的餘數:

search.each_response {print "."} 

注Ruby中的#字符表示註釋;即#(包括)右側的同一行上的所有內容都被視爲註釋,並且不會編譯爲Ruby代碼。

print 'this ' + 'is ' + 'compiled' 
#=> this is compiled 

print 'this' # + 'is' + 'not' 
#=> this 

注意,托架{}符號封裝包含在塊內的單個可執行行。然而,你要做的是執行兩個命令。對於這一點,它可能是語義上更可讀的使用Ruby的block符號:

search.each_response do 
    print '.' 
    STDOUT.flush 
end 
+0

雖然我沒有低調,但因爲你是正確的,所以使用分號和單行有時候比將語句分成單獨的行更有意義。 –

+0

我會嘗試使用一個單一的行,並將其分成單獨的行 - 我是一個noob,無論如何我需要這種做法! – user2876778

+0

謝謝zeantsoi – user2876778

-1

了嗎塊的find_item最後一行是:

search.each_response {print "."; #stdout.flush} 

凡紅寶石#標誌着註釋的開始。您已經註釋了該行的其餘部分,但不打開支架{。缺乏關閉是你錯誤的根源。

爲了讓您的代碼正確無誤,您應該將#更改爲$以訪問全局stdout對象。

+0

@zeantsoi我錯過了什麼嗎? –

+0

不,我曾意外地將它做成我的意圖,但是我無意中對您的答案進行了編輯。我後來回滾了我的編輯。 – zeantsoi

+0

我有兩個dowvotes來描述問題中的問題?我們現在是否因爲正確而被低估?如果任何一位下決心留下了評論,就像你推薦的那樣,或許這個答案不會令人不滿。 –

0

而不是#stdout.flush,鍵入$stdout.flush