OS #
Shell #
返回 True 表示成功,一共有 6 种用法,以下两种最常用,特别是第二种。
第一种
ret = system 'ls'
puts ret
第二种
ret = `ls`
puts ret
命令行 #
输入输出 #
输出
print
输出字符串
puts
输出字符串并换行
输入
gets
获得一行输入,通常使用 gets.chomp
去掉最后的换行符
输出 `puts` 和 `print`,前者输出后会追加换行,后者不会
等待输入
```ruby
print 'How old are you? '
age = gets.chomp
print 'How tall are you? '
height = gets.chomp
print 'How much do you weigh? '
weight = gets.chomp
puts "So, you're #{age} old, #{height} tall and #{weight} heavy."
需要注意如果使用了命令行参数(如:ruby foo.bar 100
)时,标准的 gets
会试图从命令行参数中读取值而不是等待用户输入,这时必须明确使用 STDIN.gets
来替代。
命令行参数 #
ARGV
在 Ruby 中表示命令行参数。可以使用 first, second, third = ARGV
的语法将 ARGV
进行解包后赋值给左边定义的变量,且参数个数大于或小于变量个数都不会引起异常。或者也可以使用 $0
这样的内置变量直接指向对应的命令行参数的值。
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}"
使用以下命令运行上述代码
ruby 03_console.rb one two three
获得结果为
03_console.rb
one
two
three