2016-11-11 26 views
3

使用以下代碼:在Ruby中,循環中的返回值是什麼?

def get_action 
    action = nil 
    until Guide::Config.actions.include?(action) 
     puts "Actions: " + Guide::Config.actions.join(", ") 
     print "> " 
     user_response = gets.chomp 
     action = user_response.downcase.strip 
    end 
    return action 
    end 

下面的代碼把用戶的響應,並最終返回其行動的另一種方法。我知道一個循環會重複直到它最終破裂,但對返回值很好奇,所以我可以更好地構造下一次循環。在until循環中,我很想知道until循環返回的值是什麼,如果有返回值呢?

+0

你是問'x'會是什麼,如果你'x = until .... end'? –

+0

詢問函數返回值是什麼,直到某個條件.... end(甚至不一定是這個例子,但一般情況下),類似於方法的返回值如何作爲最後一行或何時使用'return'關鍵字 – developer098

+0

'return'打破循環。按照mits的說法賦值'x = ... etc',將'nil'賦給'x'。 –

回答

3

循環(loopwhileuntil等)的回報可以是任何你發送給break

def get_action 
    loop do 
    action = gets.chomp 
    break action if Guide::Config.actions.include?(action) 
    end 
end 

def get_action 
    while action = gets.chomp 
    break action if Guide::Config.actions.include?(action) 
    end 
end 

,或者您可以使用begin .. while

def get_action 
    begin 
    action = gets.chomp 
    end while Guide::Config.actions.include?(action) 
    action 
end 

或前夕ñ短

def get_action 
    action = gets.chomp while Guide::Config.actions.include?(action) 
    action 
end 

PS:環本身返回零結果(隱break這是break nil),除非您使用顯式break "something"。如果你想分配循環的結果,你應該使用break這個:x = loop do break 1; end

+0

因此,循環不會返回任何內容,除非您在break方法中使用'break'語句和'break'語句與'return'類似地工作? – developer098

+0

break會從循環本身返回一些東西,因此您可以將其分配給變量並繼續執行方法。 'return'會立即退出一個方法。 – fl00r

+1

@ programmer321:是的,'break'會a)立即終止循環,並且b)使循環的計算結果與傳遞給'break'的值完全一樣,即return將立即終止一個方法(或lambda),並且使方法調用評估爲傳遞給'return'的值,'next'將立即終止一個塊並使該塊評估爲傳遞給next的值。主要的區別是,如果各個關鍵字不是*使用,會發生什麼情況:塊,方法和lambda表達式(以及模塊和類定義)評估爲最後一個表達式的值,評估結果爲 –