2015-05-22 119 views
1

我使用一個陣列上的方法。每一個string.split紅寶石。每個陣列上從方法分割字符串

def my_function(str) 
    words = str.split 
    return words #=> good, morning 
    return words[words.count-1] #=> morning 

    words.each do |word| 
     return word 
    end 
end 

puts my_function("good morning") #=> good 

與任何多詞串的結果,我只得到具有麻煩第一個字,不是每個字。在這個例子中,我不明白爲什麼當第二項清楚地存在於數組中時,我沒有得到「好」和「早上」。

同樣,使用while循環給了我相同的結果。

def my_function(str) 

words = str.split 
i = 0 
while i < words.count 
    return word[i] 
    i += 1 
end 

puts my_function("good morning") # => good 

任何幫助表示讚賞。提前致謝!

+0

'return'立即退出函數。你想用'return'語句完成什麼? –

+0

在第一個示例中,使用'return words',返回數組。使用'p my_function(「早上好」)'打印更清晰。 –

+0

您的預期產出是多少? – spickermann

回答

1

在紅寶石return語句用來從一個Ruby方法返回一個或多個值。所以你的方法將從return words退出。

def my_function(str) 
    words = str.split 
    return words # method will exit from here, and not continue, but return value is an array(["good", "morning"]). 
    return words[words.count-1] #=> morning 
    .... 
end 

puts my_function("good morning") 

輸出:

good 
morning 

,如果你想使用each方法輸出的話,你可以這樣做:

def my_function(str) 
    str.split.each do |word| 
     puts word 
    end 
end 

def my_function(str) 
    str.split.each { |word| puts word } 
end 

my_function("good morning") 

輸出:

good 
morning 
1

你假設return words返回數組到你外puts函數,它是真實的。然而,一旦你回來,你離開的功能,永不回頭,除非你明確地再次調用my_function()(你沒有),在這種情況下,你會從函數的重新開始。

如果你要打印的值停留在功能,而你需要使用

def my_function(str) 
    words = str.split 
    puts words #=> good, morning 
    puts words[words.count-1] #=> morning 

    words.each do |word| 
     puts word # print "good" on 1st iteration, "morning" on 2nd 
    end 
end 

my_function("good morning")