2016-11-10 61 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会自动返回上一个值。

相关问题