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'
     help_msg <<~HELP
     helpmsg = <<~HELP
     #{EXECUTABLE} [-h]
     #{EXECUTABLE} [-h]


     DESCRIPTION:
     DESCRIPTION:
       does things
       says hello


     PARAMS:
     PARAMS:
       $1: foo
       -n --name:
        assign a name
 
    EXAMPLE:
      #{EXECUTABLE} -n my-name
 
     HELP
     HELP
     puts(help_msg)
     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}")