我有两个“ rb”文件: SimpleCal.rb, cli.rb
SimpleCal.rb->代码
class SimpleCal
#adding two numbers
def addition_function(n1,n2)
n1 + n2
end
#subtracting two numbers (Validation:n2 shouldn't be greater than n1)
def subtract_function(n1,n2)
if n1<n2
puts "Error:Negative"
else
n1 - n2
end
end
#multiplication (Validation:n1 & n2 shouldn't be 0)
def multiplication_function(n1,n2)
if n1 == 0 || n2 == 0
puts "Warning:Result will be zero"
else
n1 * n2
end
end
#divison (Validation:n2 shouldn't be 0)
def division_function(n1,n2)
if n2 == 0
puts "Warning:Division by zero"
else
n1 / n2
end
end
end
说明: 我正在尝试提供用于简单计算器的方法功能以及验证。
clir.rb->代码(thor)
require 'thor'
require 'SimpleCal'
class MyCLI < Thor
desc "add", "Addition of two numbers"
#making use of options to provide values in terminal to add
option:n1, :type => :numeric
option:n2, :type => :numeric
#thor:add command(should call the method "addtion function from SimpleCal.rb" and add the values provided through "options" in terminal)
def add
puts "n1: #{options[:n1]}"
puts "n2: #{options[:n2]}"
obj = SimpleCal.new
res = obj.addition_function(options[:n1],options[:n2])
puts "Addtion ->#{res}"
end
def mul
puts "n1: #{options[:n1]}"
puts "n2: #{options[:n2]}"
obj = SimpleCal.new
res = obj.multiplication_function(options[:n1],options[:n2])
puts "Multiplication ->#{res}"
end
def sub
puts "n1: #{options[:n1]}"
puts "n2: #{options[:n2]}"
obj = SimpleCal.new
res = obj.subtract_function(options[:n1],options[:n2])
puts "Subtract ->#{res}"
end
def div
puts "n1: #{options[:n1]}"
puts "n2: #{options[:n2]}"
obj = SimpleCal.new
res = obj.subtract_function(options[:n1],options[:n2])
puts "Divison ->#{res}"
end
end
MyCLI.start(ARGV)
说明: cli.rb文件应从SimpleCal.rb文件调用方法函数以执行简单的计算器功能。计算器的值应使用“选项”通过终端传递 预期产量: 红宝石cli mul --n1 2 --n2 3 n1:2 n2:3 乘法:6
错误:
./cli.rb:15:in `add': undefined method `new' for SimpleCal:Module (NoMethodError)
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:54:in `<main>'
感谢您的帮助(我是新手)
答案 0 :(得分:1)
错误表明SimpleCal是一个模块,但是您显示的代码将其定义为一个类。
检查(您已经保存了SimpleCal.rb
文件)并指向您认为是文件的副本。