Ruby:未定义局部变量或方法“n1”(NameError)

Ruby :undefined local variable or method `n1' (NameError)

我是 ruby 的新手。我在 class 中继承了雷神 gem。 class 应该执行将两个数字相加的任务。

代码:

require 'thor'
class MyCLI < Thor
  desc "add", "Addition of two numbers"
  option:n1, :type => :numeric
  option:n2, :type => :numeric
   def add
     puts "n1: #{options[:n1]}"
     puts "n2: #{options[:n2]}"
     res = n1 + n2
     puts "Addtion ->#{res}"
   end

end

MyCLI.start(ARGV)

如您所见,我在代码中使用了方法选项。在终端中,我应该按以下方式提供 n1 和 n2 的输入值: ->ruby cli.rb 添加 --n1 2 --n2 1 预期产出 -> 3 但是我得到一个错误 -> n1: 1 n2: 2

./cli.rb:14:in `add': undefined local variable or method `n1' for #<MyCLI:0x00000000033bf468> (NameError)
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/thor-0.20.0/lib/thor/command.rb:27:in `run'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/thor-0.20.0/lib/thor/invocation.rb:126:in `invoke_command'

        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/thor-0.20.0/lib/thor.rb:387:in `dispatch'
        from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/thor-0.20.0/lib/thor/base.rb:466:in `start'
        from ./cli.rb:20:in `<main>'

您的 puts 调用显示访问选项值的正确方法:options[:n1]

res = options[:n1] + options[:n2]