我是红宝石的新手。我正在课堂上继承宝石。班级应执行将两个数字相加的任务。
代码:
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的输入值: ->红宝石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>'
答案 0 :(得分:1)
您的puts
调用显示访问选项值的正确方法:options[:n1]
。
res = options[:n1] + options[:n2]