首页 > 解决方案 > Ruby:未定义的局部变量或方法'n1'(NameError)

问题描述

我是红宝石的新手。我在班上继承了雷神宝石。该类应该执行将两个数字相加的任务。

代码:

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 add --n1 2 --n2 1 Expected Output -> 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>'

标签: rubythor

解决方案


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

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

推荐阅读