2016-11-10 18 views
-2

所以我一直在整理過程中Codecademy網站後使用Ruby亂搞首次上升到「面向對象編程,第一部分」和我決定開始製作計算器。出於某種原因,雖然,我得到這個錯誤:我試圖設計一個簡單的Ruby計算器,我得到一個錯誤

calc.rb:13:in `addition': undefined local variable or method `user_input' for main:Object (NameError) 
    from calc.rb:21:in `<main>' 

我很困惑,爲什麼不看我的「USER_INPUT」陣列。它超出了方法的範圍嗎?我初始化錯了嗎?

下面的代碼,所以你可以看到自己,這顯然是沒有什麼複雜,這還不算完。我只是試圖現在測試補充。

#!/usr/bin/env ruby 

user_input = Array.new 

puts "Would you like to [a]dd, [s]ubtract, [m]ultiply, or [d]ivide? " 

type_of_math = gets.chomp 

def addition 
    operator = :+ 
    puts "Please enter the numbers you want to add (enter \"=\" to stop adding numbers): " 
    until gets.chomp == "=" 
    user_input << gets.chomp.to_i 
    end 
    sum = user_input.inject(operator) 
    return sum 
end 

case type_of_math 
when "a" 
    addition 
when "s" 
    puts "Test for subtraction" 
when "m" 
    puts "Test for multiplication" 
when "d" 
    puts "Test for division" 
else 
    puts "Wrong" 
end 
+1

「是該方法的範圍?」是。 – meagar

+0

@Vanram注意'直到gets.chomp == 「=」'和'USER_INPUT << gets.chomp.to_i'都將讀取一行。這可能不是你想要的。 – Stefan

+0

@Stefan你會如何解決這個問題? – Vanram

回答

0

考慮一下你的代碼中未經測試的變體。它更慣用:

def addition 
    user_input = [] 
    puts 'Please enter the numbers you want to add (enter "=" to stop adding numbers): ' 
    loop do 
    input = gets.chomp 
    break if input == '=' 
    user_input << input 
    end 
    user_input.map(&:to_i).inject(:+) 
end 

請注意,它將user_input放入方法中。它還使用空數組的正常[]直接分配進行初始化。而不是chomp.to_i,因爲它是進入等待做,直到循環退出之後的每個值。

代替while循環,可以考慮使用loop do。掃描代碼時,它們更容易被看到。

還要注意有沒有return在方法結束。 Ruby會自動返回上一個值。

相關問題