ruby笔记

 1.输出
print
puts 换行输出
p 输出程序执行情况

2.计算
x=10
y=20
z=30
count=x+y+z
print "count=",count,"\n"

3.判断
a=20
if a >= 10
  print "bigger\n"
else 
  print "smaller\n"
end

4.从文件中读取内容
写法一
file = File.open("chek1.rb")
text = file.read
print text
file.close

写法二
file = File.open("chek1.rb")
file.each_line do |line|
  print line
end
file.close

5.正则
puts /cde/ =~ "abcdefgh"
结果为2(下标)
puts /abc/ =~ "abcdefgh"
结果为0
puts /zzz/ =~ "abcdefgh"
结果为 (空)。


file = File.open("chek1.rb")
file.each_line do |line|
  if /chek1/ =~ line
    print line
  end`-+
end
file.close
输出包含chek1的行

6.循环
(1)each
(2)each_with_index 带index循坏

names = ["aa","bb","cc","dd"]
names.each do |name|
  puts name 
end

(1)chek1
file = File.open("/etc/login.defs")
file.each_line do |line|
  if /PASS_MAX_DAYS/ =~ line and /99999/ =~line
    print true
  end
end
file.close

优化后:
file = File.open("/etc/login.defs")
file.each_line do |line|
  if /^PASS_MAX_DAYS/ =~ line
    column = line.split       #字符串分隔,默认分隔符为空格
    num = column[1]
    p (num == "99999")
  end
end
file.close


(2)chek2
file = File.open("/etc/shadow")
file.each_line do |line|
  if /zabbix:!!:16175:0:99999:7:::/ =~ line
    print true
  end
end
file.close

str = "zabbix:!!:16175:0:99999:7:::"
column = str.split(/:/)
num = column[4]
p (num == "99999")

优化后:
file = File.open("/etc/shadow")
file.each_line do |line|
  if /zabbix/ =~ line        #原字符串为zabbix:!!:16175:0:99999:7:::
    column = line.split(/:/)
     num = column[4]
     p (num == "99999")      #输出true或false,结果打印true
  end
end
file.close


1.获取键盘输入
(1)
puts "what is your name?"

$name = STDIN.gets

puts "hi "+$name
(2)ruby test.rb abc 123
puts ARGV[0]
puts ARGV[1]

2.hash存取值
hash = Hash.new
hash.store("before",arr1)
hash.store("after",arr2)

hash["before"]
hash["after"]

3.获取当前系统时间,时间格式化
now = Time.new
now = now.strftime("%Y-%m-%d %H:%M:%S")

4.复制文件
require "fileutils"
FileUtils.cp("1.rb","2.rb")

posted @ 2018-12-27 16:32  大飞90  阅读(137)  评论(0编辑  收藏  举报