Ruby基本语法
一、打印
2、注释 #
3、数学表达式
puts 3+2+4%2
puts "Hens", 25+30/6 -> Hens 30
puts "Is it greater?", 5>-2 -> Is it greater? True
4、变量与命名
cars = 100
my_name = 'Paul'
5、打印中字符串插值
(1)%s %[ , ]
puts "He's got %s eyes and %s hair." %[my_eyes, my_hair] %['eyes', 'hair']
6、字符串拼接
w = "Hello"
e = "World!"
puts w+e -> Hello World!
7、段打印
puts << PARAGRAPH
There's ...
PARAGRAPH
二、接收输入
1、age = get.chomp()
注意: 当代码中出现ARGV时使用STDIN
lives = STDIN.gets.chomp()
2、STDIN.gets
区别:gets包含了"\n", 而gets.chomp不包含"\n"
3、参数解包
(1)first, second, third = ARGV
puts "The script is called: #{0}"
puts "The first variable is: #{first}"
puts "The second variable is: #{second} "
puts "The third variable is: #{third}"
$0 脚本本身名称保存在特殊变量$0里
(2)user = ARGV.first
puts "Hi #{user}, I'm the #{$0} script."
(3)input_file = ARGV[0]
三、文件操作
1、创建
txt = File.open(filename, 'w') #'w'写 'r'读 'rb'二进制 'a'追加
txt = File.new(filename, 'w')
2、读文件
puts txt.read()
indate = txt.read()
3、清空文件
txt.truncate(txt.size)
4、写文件
txt.write(line1)
5、关闭文件
txt.close()
6、remind 标志位移动
f.seek(0, IO::SEEK_SET) #(偏移量,标志位)
标志位说明: SEEK_CUR 当前位置 SEEK_SET 文件开头 SEEK_END 文件结尾
current_file = File.open(input_file)
puts current_file.read() #这个行为导致光标到达文件结尾
current.seek(0) #回到开头,默认标志位SEEK_CUR
四、函数
1、def puts_two(*args)
arg1, arg2 = args
puts "arg1: #{arg1}, arg2: #{arg2}"
end

浙公网安备 33010602011771号