2013-06-12 23 views
0

我不明白爲什麼這種方法不起作用。當我輸入一個應該通過if語句的值時,它不起作用。Ruby中的遞歸不是像我認爲它應該

def getBase 
    puts "What is the base URL for the test?" 
    x = gets 
    if (x.include? 'http://') && ((x.split('.').at(x.split('.').length - 1).length) == 3) 
     return x 
    else 
     puts "That is in the incorrect format." 
     puts "Please format your url like this" 
     puts "http://example.com" 
     getBase 
    end 
end 

輸入「http://test.com

結果:語句重複,並當你輸入與gets它包括在最後的換行符\n(從用戶按下回車即可)不退出遞歸

+0

我們需要更多的信息。你的測試輸入是什麼?結果是什麼?你爲什麼期望它以這種方式工作?你的'if'條件相當混亂 - 你想用它做什麼? – iamnotmaynard

+0

我希望在多次嘗試失敗後返回x。我已經測試了&&兩側的條件,他們似乎以我認爲的方式工作。 – Zach

+2

IMO,這是不是一個特別好的地方使用遞歸......這很好,如果它只是一個例子,但如果你所做的只是等待,直到用戶最終輸入一個有效的文本字符串爲什麼你不使用循環?另外,如果我將條件替換爲有效的條件(例如'/^http:\/\ /(。+ \。)+。+ $ /。match(x)'),它對我來說運行良好。這個原因在iamnotmaynard的帖子中有解釋。 – mdunsmuir

回答

2

。所以你的x實際上是"http://test.com\n"

爲了擺脫這種使用String#chomp的:

x = gets.chomp 

應該這樣做。

+0

另外,我認爲他應該''返回'else'語句中的'getBase'調用... –

+0

else中的返回是隱含的 – Zach

+0

這會使它更清楚,但它不是必須的,因爲Ruby會自動返回最後的聲明。 – iamnotmaynard

1

如果目的是強制使用正確的URL格式和/或確保它是HTTP URL,那麼爲什麼不使用專門設計的工具呢? Ruby的URI類是你的朋友:

require 'uri' 

URI.parse('http://foo.bar').is_a?(URI::HTTP) 
=> true 

URI.parse('ftp://foo.bar').is_a?(URI::HTTP) 
=> false 

URI.parse('file://foo.bar').is_a?(URI::HTTP) 
=> false 

URI.parse('foo.bar').is_a?(URI::HTTP) 
=> false 

我會寫代碼更是這樣的:

require 'uri' 

def get_base 
    loop do 
    puts "What is the base URL for the test?" 
    x = gets.chomp 
    begin 
     uri = URI.parse(x) 
     return uri.to_s if uri.is_a?(URI::HTTP) 
    rescue URI::InvalidURIError 
    end 
    puts "That is in the incorrect format." 
    puts "Please format your URL like this:" 
    puts 
    puts " http://example.com" 
    end 
end 

puts "Got: #{ get_base() }" 
相關問題