Ruby 的新手,尝试构建最简单的计算器,为什么它不起作用?

New to Ruby, tried to build the simplest calculator, why is it not working?

class Calculator
  def firsti
    puts "Please type first number: "
  end

  def initialize(x)
    @x = gets.chomp
  end

  def opi
    puts "Please type operation: "
  end

  def initialize(y)
    @y = gets.chomp
  end

  def secondi
    puts "Please type second number: "
  end

  def initialize(z)
    @z = gets.chomp
  end

  if @y == '+'
    puts @x+@z
  elsif @y == '-'
    puts @x-@z
  elsif @y == '*'
    puts @x*@z
  elsif @y == '/'
    puts @x/@z
  else
    puts "Something went wrong. Please try again."
  end
end

用空格试过,有或没有 ()-s,没有错误消息,我可能只是个菜鸟。任何帮助,将不胜感激。最初尝试使用没有 class 的简单变量,即使我只写一个简单的

也没有结果
x = 2
y = +
z = 3
if y == '+'
  puts x+z
end

它奏效了。似乎无法理解问题所在。

这是您的代码的 "working version",我已尝试对您的设计进行最小改动:

class Calculator 

  def initialize 
    puts "Please type first number: " 
    @x = gets.chomp.to_i 
    puts "Please type operation: " 
    @y = gets.chomp 
    puts "Please type second number: " 
    @z = gets.chomp.to_i 
  end 


  def result 
    if @y == '+' 
      @x+@z 
    elsif @y == '-' 
      @x-@z 
    elsif @y == '*' 
      @x*@z 
    elsif @y == '/' 
      @x/@z 
    else 
      "Something went wrong. Please try again." 
    end 
  end 

end 

calculator = Calculator.new 
puts "Result is:" 
puts calculator.result

您的代码存在多个问题,无法按预期工作:

  • 您在单个 class 中定义了 多个 initialize 方法。这不可能;您实际上所做的只是*重新*定义相同的方法。
  • 你的代码没有流控意识。您的印象似乎是"the code will all just run, from top to bottom"。这不是 methods/classes 的工作方式;你首先定义methods/classes,然后调用它们。正如您在我的代码中看到的那样,我显式地创建了一个 Calculator 对象(Calculator.new - 构造一个新实例,调用 initialize 方法),然后调用 result方法。
  • 类似地,您正在对 @y 变量执行条件检查,在代码执行的此时 尚未定义 !当您的 if 语句执行时,@y 将是 nil;因此,逻辑落到了 else 语句。
  • 更微妙的一点是,gets 命令的输入始终是 String。您需要调用 to_i 将其转换为 Integer;否则,您会得到有趣的结果,例如:"2" + "5" == "25"