2013-01-03 128 views
1

我是新來編碼,所以請自由指出我引用代碼的方式的任何錯誤。紅寶石範圍打印額外

rows = 5 
(1..rows).each do |n| 
    print n, ' ' 
end 

這打印出我期望的結果:1 2 3 4 5

但是,當我把它變成一個方法:

def test(rows) 
    (1..rows).each do |n| 
    print n, ' ' 
end 
end 

puts test(5) 

我得到1 2 3 4 5 1..5

爲什麼1..5顯示?我該如何擺脫它?

我在方法中需要它,因爲我打算向它添加更多的代碼。

回答

0

Ruby函數將返回最後一條語句,在您的案例1..5中。爲了說明我給它一個不同的返回值:

def test(rows) 
    (1..rows).each {|n| puts "#{ n } "} 
    return 'mashbash' 
end 

# Just the function invokation, only the function will print something 
test(5) # => "1 2 3 4 5 " 

# Same as above, plus printing the return value of test(5) 
puts test(5) # => "1 2 3 4 5 mashbash" 

你可以寫一個略有不同的例子來實現你喜歡什麼:

def second_test(rows) 
    # Cast range to an array 
    array = (1..rows).to_a # [1, 2, 3, 4, 5] 
    array.join(', ') # "1, 2, 3, 4, 5", and it is the last statement => return value 
end 

# Print the return value ("1, 2, 3, 4, 5") from the second_test function 
p second_test(5) 
# => "1, 2, 3, 4, 5" 
+0

謝謝,這使得它非常清晰和易於理解 – mashbash

1

each對於範圍返回循環完成後的範圍,並且您可能也打印了返回值test

只要運行test(5)而不是puts test(5)什麼的。

+0

謝謝但是爲什麼1..5會在我使用'puts'時出現?我認爲測試的回報價值就是範圍本身。 – mashbash

+0

是的,範圍是'1..5',所以你得到'1..5'作爲輸出。 – Dogbert

1

Ruby總是返回任何函數的最後一行。

您正在執行puts test(5),並且test(5)會打印您期望的數據,並且額外的puts會打印出由test(5)方法返回的數據。

希望能回答你的問題。

+0

好的,這很有道理,謝謝! – mashbash

1

最後1..5是從腳本返回值。當你在IRB中運行代碼時,你會得到這個結果。當你將它作爲獨立的Ruby腳本運行時,它不會顯示出來,所以你不必擔心它。