新手问题 gets 和 ARGV 的小疑问

xdz0611 · September 08, 2014 · Last by windwiny replied at September 10, 2014 · 2153 hits

cat a.rb

puts "argv length is #{ARGV.length}"
puts "Post title: "
title = gets.chomp
puts "your input title is #{title}"

puts "argv length is #{ARGV.length}"
puts "Post body: " if ARGV.length == 0
body = ARGF.gets.chomp
puts body

例如:ruby a.rb /etc/passwd

上面这段代码中,如果给了 命令行参数,title 就是从第一个参数文件中获取的,如果没有的话,就是从 stdin 获取。gets 本来就是这么用的吗?gets 的对象到底是谁?

第二个问题是,如果给了命令行参数,第二次打印出来的 ARGV 长度已经 -1 了,这里应该是 gets 的作用, 为什么 gets 操作之后,ARGV 的元素变少了

就是这样的功能

gets(sep=$/)  string or nil click to toggle source 
gets(limit)  string or nil 
gets(sep,limit)  string or nil 
Returns (and assigns to $_) the next line from the list of files in ARGV (or $*), or from standard input if no files are present on the command line. Returns nil at end of file. The optional argument specifies the record separator. The separator is included with the contents of each record. A separator of nil reads the entire contents, and a zero-length separator reads the input one paragraph at a time, where paragraphs are divided by two consecutive newlines. If the first argument is an integer, or optional second argument is given, the returning string would not be longer than the given value in bytes. If multiple filenames are present in ARGV, +gets(nil)+ will read the contents one file at a time.

#1 楼 @windwiny 请教除了官网 这里能查到这个定义之外。能否从命令行直接查询该文档? 比如 ri gets 我得到的结果跟上面的不太一样

可能版本不一样吧。

我都是下载 chm 格式的文档,几个版本都有。

You need to Sign in before reply, if you don't have an account, please Sign up first.