Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

stdin - What's the point of ARGV in Ruby?

What's the point of ARGV in Ruby?

first, second, third = ARGV 
puts "The script is called: #{$0}"
puts "Your first variable is: #{first}"
puts "Your second variable is: #{second}"
puts "Your third variable is: #{third}"

What's the point of this when to run the file I need to do:

ruby ex1.rb

and to put in the first, second and third variables I need to type in

ruby ex1.rb blah blah blah

How does this benefit at all the person running the program? They can't do it anyway since I'd assume it be an executable:

user = ARGV.first
prompt = '> '

puts "Hi #{user}, I'm the #{$0} script."
puts "I'd like to ask you a few questions."
puts "Do you like me #{user}?"
print prompt
likes = STDIN.gets.chomp()

puts "Where do you live #{user}?"
print prompt
lives = STDIN.gets.chomp()

puts "What kind of computer do you have?"
print prompt
computer = STDIN.gets.chomp()

puts <<MESSAGE
Alright, so you said #{likes} about liking me.
You live in #{lives}.  Not sure where that is.
And you have a #{computer} computer.  Nice.
MESSAGE

Can someone please explain this to me?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What's the point of ARGV in Ruby?

ARGV "contains the arguments passed to your script, one per element."

What's the point of this when to run the file you need to do: ruby ex1.rb and to put in the first, second and third variables you need to type in ruby ex1.rb blah blah blah.

That is the exact point, to be able to specify arguments when running the file like:

ruby ex1.rb -a -b 3

How does this benefit at all the person running the program?

Same benefit any other command-line program gets from being able to do so: the user can specify upfront what they want, and it's easier to script than an interactive CLI.

They can't do it anyway since I'd assume it be an executable.

Yes, they can. You just gave an example of exactly how the user would run your program that way. Whether it's executable or not doesn't change anything.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...