I have to use this command to run my ruby
program:
$ruby filename.rb NAME --from="People" --yell
And I have the script like this:
require 'thor'
class CLI < Thor
desc "hello NAME", "say hello to NAME"
method_option :from, :required => true
method_option :yell, :type => :boolean
def self.hello(name)
output = []
output << "from: #{options[:from]}" if options[:from]
output << "Hello #{name}"
output = output.join("\n")
puts options[:yell] ? output.upcase : output
end
end
CLI.hello(ARGV)
When I run the code, I get the following output:
c:\RubyWorkplace\Assignment1>ruby testing.rb Jay --from="Ray"
FROM: #<THOR::OPTION:0X000000031D7998>
HELLO ["JAY", "--FROM=RAY"]
c:\RubyWorkplace\Assignment1>ruby testing.rb Jay --from="Ray" --yell
FROM: #<THOR::OPTION:0X0000000321E528>
HELLO ["JAY", "--FROM=RAY", "--YELL"]
It looks like :yell
always works no matter I specify it or not, and options
are all read as name
input in the hello
method.
I found and tried many ways from online tutorials but the problem wasn't solved. Please tell me what has been gone wrong. Thank you!
The problem is caused by I am calling CLI.hello ARGV
in the script. when the program runs, it will call hello
method and recognize all command line inputs as hello
's parameter, which is an array.
One of the ways to fix this problem is making hello
public by removing self
, the call the script by start
method.
require 'thor'
class CLI < Thor
desc "hello NAME", "say hello to NAME"
method_option :from, :required => true
method_option :yell, :type => :boolean
def hello(name)
#do something
end
end
CLI.start ARGV