Search code examples
rubycommand-line-argumentsflags

How to provide flags to ruby script like -v , -o and place code accordingly?


I have created one ruby script that I want to run with some flags on console say -v flag prints output on console and -o stores output in new file with file name I am taking from console using gets()

My code has following structure:

puts "Enter filename to analyze:\n\n"
filename = gets().chomp
puts "Provide filename to store result in new text file:\n\n"
output = gets().chomp
filesize = File.size(filename)
puts "File size in Bytes:\n#{filesize.to_i}\n"
pagecontent = filesize - 20
puts "\n\nData:\n#{pagecontent}\n\n"
File.open(filename,'r') do |file|
         #whole process with few do..end in between that I want to do in 2 different #ways.
    #If I provide -v flag on console result of this code should be displayed on console
    #and with -o flag it should be stored in file with filename provided on console #stored in output variable declared above
end
end

Solution

  • Use stdlib OptionParser