rubythor

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


I am a newbie in ruby. I am inheriting thor gem within my class. The class should perform the task of adding two numbers.

Code:

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)

As you can see I am making use of method options within my code. In the terminal I should provide the input values for n1 and n2, in the following way: ->ruby cli.rb add --n1 2 --n2 1 Expected Output -> 3 But I got an error -> 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>'

Solution

  • Your puts calls show the correct way to access the option values: options[:n1].

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