ruby之基础语法
2024-10-07 15:18:09
ruby语法之哈希 =》相当于python的字典
ruby语法之数组 =》相当于python的列表
举例:
gitaly= Hash.new #建立新Hash类型
gitaly['first']="myfirst"
gitaly['storage'] = [
{
'name' => 'default',
'path' => '/tmp/path-1'
},
{
'name' => 'nfs1',
'path' => '/mnt/nfs1'
}
]
puts gitaly #{"first"=>"myfirst", "storage"=>[{"name"=>"default", "path"=>"/tmp/path-1"}, {"name"=>"nfs1", "path"=>"/mnt/nfs1"}]}
puts gitaly.keys #first storage
puts gitaly['storage'][0] #{"name"=>"default", "path"=>"/tmp/path-1"}
puts gitaly['storage'][-1] #{"name"=>"nfs1", "path"=>"/mnt/nfs1"}
puts gitaly.size # test=[] #新的空的数组类型
test[0]="a"
test[1]='k'
puts test # a k 数组的增:
test << "b" #["a","k","b"]
test.push("b") #数组尾部增加元素
test.xshift("b") #头部增加元素
数组的删:
test.pop #后面不加元素,依次从尾部删除一个元素
test.shift #后面不加元素,依次从头部删除一个元素
test.delete("a") #删除元素a ,有多个a都删除
test.delete_at(2) #删除某个索引位置的元素
数组的去重:bb=test.uniq #不改变test的值,改变原数组用uniq!
数组变成字符串:kk=["a","b","a"];bb=kk.join("-") # a-b-a 使用某个符合连接,可以是多个字符
将字符串变成数组:kk="abcd";bb=kk.split(//) #【"a","b","c","d"】
数组的排序:kk=["a","b","a"];bb=kk.sort;puts bb # a a b
查看数据的类型
aa='aa'
puts aa.class
ruby语法之处理字符串
puts aa 改
aa='hello world'
aa['hello']='first' #匹配第一个符合条件的字符串,区别python的字符串
puts aa #first world
puts aa.class #string aa='hello world'
aa[0..4]='first'
puts aa #first world
puts aa.class #string aa='hello world hello'
aa.gsub('hello','first') #替换所有符合条件的字符串
puts aa #hello world hello
puts aa.class #string aa='hello world'
aa.insert 5,' my' #在指定位置插入字符串
puts aa #hello my world
puts aa.class #string
增
kk='abc'
kk<<'def' #用来拼接字符串
puts kk #abcdef 删
#chomp和chomp!的区别是 chomp!会改变原字符串
aa='hello world!'
aa.chop! #删除最后一个字符,改变了原字符串,使用chop不会改变原来的字符串
puts aa # hello world
puts aa.class #string #删除尾部指定单个字符或者字符串
aa="hellohello"
bb=aa.chomp!("o") #或者 bb=aa.chomp!("llo"),但是里面如果是he的话,bb就是空值,aa不变
puts aa #hellohell
puts bb #hellohell
#删除开头第一个字符
str[0]=""
#删除结尾最后一个字符
str[-1]=""
#使用delete方法删除指定字符串,deleteh和delete!区别和chomp类似
puts "hello".delete "abcdefghijkl" #o #tr和tr! 修改成对应的字符,一个一个比对,没有则替换成前面一个替换的字母
"hello".tr!("lexyz","pi") #hippo
hello".tr("lho","km") #mekko -> l替换成k h替换成m,o也替换成m
#到这里发现tr命令很强大啊,那么可以用它来删除了
hellohello".tr("lh","") #eoeo
ruby插件之json将字符串转化成哈希
#!/usr/bin/ruby require 'json'
aa="{\"a\":\"1\",\"b\":\"2\"}" #字符串,json里面没有单引号
bb=JSON.parse(aa) #使用json进行转化
puts bb.class #类型变为Hash
puts bb["c"] #没有不报错,但是为空
puts bb["a"] # 1
puts bb # {"a"=>"1", "b"=>"2"}
ruby读入文件 IO.readlines
[root@orl11-infa ~]# cat test1.rb
#!/usr/bin/ruby arr=IO.readlines("tt.txt")
puts arr.class
puts arr
puts "------------------------"
puts arr[0]
[root@orl11-infa ~]# vim test1.rb
[root@orl11-infa ~]# ruby test1.rb #运行结果
Array #变成数组类型
1 first line
2 second line
------------------------
1 first line
ruby之写入文件
#先清空后写入
#!/usr/bin/ruby
File.open("r2.txt", "w+") do |file|
file.puts "haha"
file.puts "heihei"
file.close()
end #后面追加
File.open("r2.txt", "a+") do |file|
file.puts "haha"
file.puts "heihei"
file.close()
end
ruby之打印文件的绝对路径
puts File.expand_path("r2.txt")
ruby之修改文件的权限
[root@orl11-infa ~]# cat test1.rb
#!/usr/bin/ruby
file=File.new("tt.txt","w")
file.chmod(0755)
[root@orl11-infa ~]# ll tt.txt
-rw-r--r-- 1 root root 27 10月 28 16:22 tt.txt
[root@orl11-infa ~]# ruby test1.rb
[root@orl11-infa ~]# ll tt.txt
-rwxr-xr-x 1 root root 0 10月 28 16:27 tt.txt
ruby语法之判断if
x=1
if x > 2
puts "x 大于 2"
elsif x <= 2 and x!=0
puts "x 是 1"
else
puts "无法得知 x 的值"
end
其他:对当前条件不做处理,使用next
ruby语法之循环
for i in 0..5
puts "局部变量的值为 #{i}"
end
ruby语法:循环each
[root@orl11-infa ~]# cat test2.rb
#!/usr/bin/ruby aa=['awk','block','cd']
aa.each do |temp|
if temp.include? 'c'
puts temp
end
end
[root@orl11-infa ~]# ruby test2.rb
block
cd
举例:根据之前logstash处理季度和search_name的问题现在完全可以用ruby语法处理
if "cdpTest" in [tags]{
grok {
match => { "message" => "\|%{DATA:userName}\|%{DATA:opreteTimeStamp}\|%{DATA:year}-%{DATA:month}-%{DATA:day} %{DATA:hour}:%{DATA:other}\|%{DATA:deviceModel}\|%{DATA:pageName}\|%{DATA:elementName}\|%{DATA:params}\|%{DATA:appKey}\|%{DATA:ssoSource}\|%{DATA:logType}\|" }
}
ruby {
code => "
bb=event.get('[month]').to_i
bb=(bb+2)/3
cc=(bb.to_s)<<'季度'
event.set('quarter',cc)
aa=event.get('[params]')
require 'json'
dd=JSON.parse(aa)
if dd['search_name']
event.set('search_name',dd['search_name'])
end
"
remove_field => [ "message" ]
}
}
}
ruby语法之计算昨天的日期
#!/usr/bin/ruby
require 'date'
day=Time.now
puts day.strftime("%Y%m%d")
day1=Date.new(day.year,day.month,day.day)
day1=(day1 - 1).strftime("%Y%m%d")
puts "昨天的日期:#{day1}"
str="hhh_v"<<day1
puts str
[root@orl11-infa ~]# ruby data.rb
20191028
昨天的日期:20191027
hhh_v20191027
到了这里,我们就会想ruby语言和shell的交互
方式一:exec 取代当前进程,不产生子进程,它执行成功后,它后面的命令不会执行
exec "curl -XGET --user elastic:pass 'http://192.168.137.10:9200/_cat/indices' >rb1.txt"
方式二:使用反引号 ``,产生子进程,后面的命令可以执行
`curl -XGET --user elastic:pass 'http://192.168.137.10:9200/_cat/indices' >rb1.txt`
方式三:使用system,产生子进程,后面的命令会执行,返回命令执行的结果(true或者false)
cmd=system "curl -XGET --user elastic:pass 'http://192.168.137.10:9200/_cat/indices' >rb1.txt"
puts cmd #true
if cmd
puts 'success'
else
puts "failure"
end
方式四:使用%x,后面的命令会执行
%x(for i in `seq 1 5`;do echo $i;done)
%x(echo "hello";echo "haha")
其他:
ruby脚本的后缀 .rb
变量放入""里面时,puts "#{kk}"
字符串转化成整形:.to_i
整形转化成字符串:.to_s
导入模块:require 'json'
ruby脚本的语法检查:ruby -c 脚本
ruby在linux命令行中执行:ruby -e 'aa="abc";if aa.include? "b";puts "ok";else "no";end'
对命令取反,使用:!(正常命令),例如满足不包括的条件 !(bb.include? temp)
字符串以什么开头:str.start_with("a")
特殊符号:\t tab键 \s 空格 \n换行 \r回车
跳出当前循环:next
退出整个循环:break
在linux的shell中输入 irb 进入ruby的语言环境,类似于输入python进入python环境
查看元素类型:puts a.class
最新文章
- 利用Photoshop修改图片以达到投稿要求
- [转载] 问题解决:FFmpeg视频编解码库,无法解析的外部信号
- 多线程/进度条应用(progressbar)
- $GLOBALS 添加超全局变量
- 『重构--改善既有代码的设计』读书笔记----Inline Temp
- make clean指令出现问题
- HTML学习笔记汇总
- java 面向对象 2
- log4j控制指定包下的日志
- 2019春下载的sublime text都无法自动安装package control:解决办法
- Docker应用:Docker-compose(容器编排)
- JavaOne 2016主旨演讲畅谈Java近期及远期规划
- bzoj千题计划204:bzoj2813: 奇妙的Fibonacci
- springboot-7-配置druid数据源监视
- 使用泛型集合取代datatable作为返回值实现面向对象
- [转]这五种方法前四种方法只支持IE浏览器,最后一个方法支持当前主流的浏览器(火狐,IE,Chrome,Opera,Safari)
- php注册审查
- OpenGL学习进程(4)第二课:绘制图形
- js实现封装和继承
- 在Windows Server 2019通过Docker Compose部署Asp.Net Core