2017-09-16 43 views
-1

我試圖創建一個新的散列(組),我將傳遞名稱,雜貨,fuel_and_accommodations和recreation_activities的值。實際上,最終我需要一個哈希嵌套在組哈希(每個旅行者)。我的問題現在的問題是,我得到這個消息:Ruby hash.new錯誤未定義的局部變量或方法...對於主對象

未定義的局部變量或方法'組 '主:對象
(REPL):5:'USER_NAME'
(REPL):18: `在enter_expenses塊
(REPL):15:在`倍
(REPL):15:在`enter_expenses'
(REPL):34:在`」

我只是學習Ruby。任何幫助將不勝感激!

group = Hash.new 

def user_name 
    puts "What is the name of this traveler?" 
    group["name"]= gets.chomp.capitalize 
end 

def enter_expenses 
    puts "Welcome to the Expense Tracker System!\n".upcase 
    puts "__________________________________________" 
    puts "\nUse this system to track your group's expenses when traveling." 
    print "Ready to get started? Enter yes to continue" 
    ready_to_expense = gets.chomp.downcase 


    4.times do 

    if ready_to_expense == "yes" 
     puts "Welcome #{user_name}! Enter your expenses below:\n" 

     puts "Amount spent on groceries:" 
     group["groceries"]= gets.chomp.to_f 

     puts "Amount spent on fuel & accommodations:" 
     group["fuel_and_accommodations"]= gets.chomp.to_f 

     puts "Amount spent recreational activities:" 
     group["recreational_activities"] = gets.chomp.to_f 

    elsif "Please come back when ready to enter your expenses." 
    end 
    end 
end 

enter_expenses 
create_travelers 

puts "__________________________________________" 
puts "Thanks for using the expense tracker system!".upcase 

回答

0

Ruby中的局部變量沒有進入方法;方法聲明他們自己的範圍,他們不像閉包。您可以使用實例變量來代替:

@group = Hash.new # NOTE @ 

... 

def enter_expenses 
... 
    4.times do 
    if ready_to_expense == "yes" 
     @group["groceries"]= gets.chomp.to_f # NOTE @ 
     ... 
    end 
    end 
end 
+0

使它成爲一個實例或全局變量不工作,要麼:(非常感謝您的答覆mudasobwa任何其他建議 – kax

+0

當然它確實有!?。 – mudasobwa

相關問題