Ruby 中的 ARGV 有什么意义? [英] What's the point of ARGV in Ruby?

查看:21
本文介绍了Ruby 中的 ARGV 有什么意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby 中的 ARGV 有什么意义?

第一、第二、第三 = ARGVputs "脚本被调用:#{$0}"puts 你的第一个变量是:#{first}"puts 你的第二个变量是:#{second}"puts 你的第三个变量是:#{third}"

什么时候运行我需要做的文件:

ruby ex1.rb

并输入我需要输入的第一个、第二个和第三个变量

ruby ex1.rb 等等

这对运行该程序的所有人有何好处?他们无论如何都做不到,因为我认为它是一个可执行文件:

user = ARGV.first提示 = '>'输入嗨#{user},我是#{$0} 脚本."输入我想问你几个问题."输入你喜欢我#{user}吗?"打印提示喜欢 = STDIN.gets.chomp()输入你住在哪里#{user}?"打印提示生命 = STDIN.gets.chomp()puts你有什么类型的电脑?"打印提示计算机 = STDIN.gets.chomp()puts <

有人可以向我解释一下吗?

解决方案

ARGV 在 Ruby 中有什么意义?

ARGV包含传递给脚本的参数,每个元素一个."

<块引用>

什么时候运行你需要做的文件:ruby ex1.rb 并放入你需要输入的第一、第二和第三个变量ruby ex1.rb 等等等等.

这就是在运行文件时能够指定参数的确切点,例如:

ruby ex1.rb -a -b 3

<块引用>

这对运行该程序的所有人有何好处?

任何其他命令行程序都可以从这样做中获得同样的好处:用户可以预先指定他们想要的内容,并且比交互式 CLI 更容易编写脚本.

<块引用>

他们无论如何也做不到,因为我认为它是一个可执行文件.

是的,他们可以.您刚刚给出了一个示例,说明用户将如何以这种方式运行您的程序.无论它是否可执行都不会改变任何东西.

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?

解决方案

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.

这篇关于Ruby 中的 ARGV 有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆