2015-11-20 65 views
0

我想這個方法遍歷名稱katz_deli的數組中的每個項目,並使用puts來顯示名稱及其索引。但是,輸出只是數組中的第一個名稱與其索引。Ruby使用each_with_index

我的代碼:

def line (katz_deli) 
    if katz_deli.count > 1 
    katz_deli.each_with_index {|name, index| puts "The line is currently: #{index +1}. #{name}" } 
    else 
    puts "The line is currently empty." 
    end 
end 

我希望我的輸出爲"The line is currently: 1. Logan 2. Avi 3. Spencer" 但是我卻越來越"The line is currently: 1. Logan."謝謝!

+0

是你確定你的陣列中有一個以上的元素嗎?如果是,請提供您陣列數據的示例 –

+2

我無法重現您的問題。當我打電話給'line'(['Logan','Avi','Spencer'])時,我得到三行輸出:'該行當前是:1. Logan','The line is currently:2. Avi', '該線目前是:3. Spencer'。 –

+0

數組是katz_deli = [「Logan」,「Avi」,「Spencer」]。我懂了。有沒有辦法讓這一切都在一條線上 - 即輸出是完全的'該行目前是:1. Logan 2. Avi 3. Spencer'我正在這樣做一個課程,我認爲這正是教練正在尋找的。謝謝! – Keren

回答

3

您可以先構建輸出字符串,puts它,一旦它已準備就緒:

input = ["Logan", "Avi", "Spencer"] 

def line (katz_deli) 
    if katz_deli.count > 1 
    output = "The line is currently:" 
    katz_deli.each_with_index do |name, index| 
     output << " #{index +1}. #{name}" 
    end 
    puts output 
    else 
    puts "The line is currently empty." 
    end 
end 

line(input) 
1
def line (katz_deli) 
    if katz_deli.count > 1 
    print "The line is currently:" 
    katz_deli.each_with_index {|name, index| print " #{index +1}. #{name}" } 
    else 
    puts "The line is currently empty." 
    end 
end