ruby - 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>'
解决方案
您的puts
调用显示了访问选项值的正确方法:options[:n1]
.
res = options[:n1] + options[:n2]
推荐阅读
- jquery - 错误:SyntaxError:JSON 中的意外标记 <
- python - Django 中 __lte 和 __gte 的区别
- java - 如何在不使用节点的情况下交替合并链表?并使用递归?
- javascript - 有没有办法覆盖 z-index
- apache-kafka - 在 Kafka 中,如何在两个偏移量之间重放 kafka 消费者?
- apache-kafka - 如何在带有 MongoDB 的 Kafka Connect Sink 连接器中获取 kafka 消息的标头
- prometheus - 如何创建查询以监控 docker 容器一天运行了多少分钟
- html - PrimeNG - 订单列表
- continuous-deployment - Archer GRC 自动部署
- angular - 迭代角材料表