2017-09-16 74 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

相关问题