2017-07-02 46 views
-2

我是一名編程和Ruby初學者,我很難找到解決問題的解決方案。Ruby代碼中的錯誤

在這裏,你可以找到我的錯誤代碼是:

def greeting  

    puts "Hello! Please type your name: " 
    name = gets.chomp.capitalize 

    puts "It is nice to meet you #{name}. I am a simple calculator application." 
    puts "I can add, subtract, multiply, and divide." 

end 

greeting 

def calc 

    puts "First number: " 
    a = gets.to_i 
    puts "Secons number: " 
    b = gets.to_i 

    puts "Type 1 to add, 2 to subtract, 3 to multiply, or 4 to divide two numbers: " 
    operation_selection = gets.to_i 

    def add 
     c = a + b 
    end 

    def subtract 
     c = a - b 
    end 

    def muliply 
     c = a * b 
    end 

    def divide 
     c = a/b 
    end 

    if operation_selection == 1 
     add 
    elsif operation_selection == 2 
     subtract 
    elsif operation_selection == 3 
     multiply 
    elsif operation_selection == 4 
     divide 
    end 

puts "Your Result is #{c}." 

end 

calc 
+2

沒有人會請點擊此鏈接。請在這裏分享你的代碼。 – Mureinik

+0

請不要發佈鏈接到您的代碼。將來將代碼插入問題中。 –

+1

你會得到什麼錯誤?用錯誤信息編輯你的問題。 –

回答

1

您不能訪問內部方法局部變量。

解決方案1:

轉換abc從局部變量實例變量(即@a@b@c)和你的代碼將正常工作。

解決方案2(推薦解決方案):

與下面的代碼替換您calc方法:

def calc 
    puts "First number: " 
    a = gets.to_i 
    puts "Second number: " 
    b = gets.to_i 

    puts "Type 1 to add, 2 to subtract, 3 to multiply, or 4 to divide two numbers: " 
    operation_selection = gets.to_i 

    output = case operation_selection 
      when 1 
      a + b 
      when 2 
      a - b 
      when 3 
      a * b 
      when 4 
      a/b 
      else 
      'Invalid input' 
      end 

    puts "Your Result is #{output}." 
end