Ruby cli: Difference between revisions
From wikinotes
Line 2: | Line 2: | ||
= Param Parsing, Raw = | = Param Parsing, Raw = | ||
<blockquote> | <blockquote> | ||
{{ example | |||
| no structure | |||
| | |||
<syntaxhighlight lang="ruby"> | <syntaxhighlight lang="ruby"> | ||
#!/usr/bin/env ruby | #!/usr/bin/env ruby | ||
Line 7: | Line 10: | ||
EXECUTABLE = File.basename(__FILE__) | EXECUTABLE = File.basename(__FILE__) | ||
name = "unknown" | |||
age = "unknown" | |||
shift = 0 | |||
ARGV.count.times do |index| | ARGV.count.times do |index| | ||
if shift > 0 | |||
shift -= 1 | |||
next | |||
end | |||
case ARGV[index] | case ARGV[index] | ||
when '-h', '--help' | when '-h', '--help' | ||
helpmsg = <<~HELP | |||
#{EXECUTABLE} [-h] | #{EXECUTABLE} [-h] | ||
DESCRIPTION: | DESCRIPTION: | ||
says hello | |||
PARAMS: | PARAMS: | ||
-n --name: | |||
assign a name | |||
EXAMPLE: | |||
#{EXECUTABLE} -n my-name | |||
HELP | HELP | ||
puts( | puts(helpmsg) | ||
exit(0) | exit(0) | ||
when '-n', '--name' | |||
name = ARGV[index+1] | |||
shift += 1 | |||
when '-a', '--age' | |||
age = ARGV[index+1] | |||
shift += 1 | |||
else | else | ||
Line 27: | Line 51: | ||
end | end | ||
end | end | ||
puts("hello, #{name} with age #{age}") | |||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- Param Parsing --> | </blockquote><!-- Param Parsing --> |
Revision as of 15:30, 29 October 2022
Param Parsing, Raw
{{ example | no structure |
#!/usr/bin/env ruby EXECUTABLE = File.basename(__FILE__) name = "unknown" age = "unknown" shift = 0 ARGV.count.times do |index| if shift > 0 shift -= 1 next end case ARGV[index] when '-h', '--help' helpmsg = <<~HELP #{EXECUTABLE} [-h] DESCRIPTION: says hello PARAMS: -n --name: assign a name EXAMPLE: #{EXECUTABLE} -n my-name HELP puts(helpmsg) exit(0) when '-n', '--name' name = ARGV[index+1] shift += 1 when '-a', '--age' age = ARGV[index+1] shift += 1 else puts "error" exit(1) end end puts("hello, #{name} with age #{age}")