ruby - ruby 命令拆分输出并检查条件
问题描述
我编写了一个 ruby 脚本来连接到 oracle 数据库,它以下面的格式获取输出,我想知道当表空间大小高于 90 时如何拆分输出并检查条件(IF split.value>90) % 然后显示关键信息
def exec_query
stdin, stdout, stderr = Open3.popen3("sqlplus -S user/pwd@dbname")
stdin.puts "tablespace script query here;"
stdin.close
puts "query executd"
out = []
until stdout.eof? do
-- added code val=out.map(&:split).select {|_,v| v.to_f > 90}
tmp = stdout.gets.chomp.strip
puts tmp
out.push tmp unless tmp.empty?
end
-- added code edit 2
if val > 90
puts "criticial"
end:q1
stdout.close
stderr.close
输出
TABLESPACE_NAME PERCENTAGE_USED
------------------------------ ---------------
SYSTEM 98.46
SYSAUX 95.15
USERS 9.32
UNDOTBS1 3.5
UNDOTBS2 2.93
TEMP
编辑1:
在输出之后,我添加了一行来检查值是否高于 90 它应该发送一条关键消息,但我收到了这个错误
if val > 90
puts "criticial"
end:q1
错误信息
test3.rb:34:in `exec_query': undefined method `>' for [["SYSTEM", "98.46"], [. "SYSAUX", "95.15"]]:Array (NoMethodError)
from test3.rb:41:in `<main>'
解决方案
一旦我们得到查询的输出,这就是一个简单的解析问题。
在这里,我使用字符串模拟了输出,stdout.each_line
效果也一样。
output = %q[TABLESPACE_NAME PERCENTAGE_USED
------------------------------ ---------------
SYSTEM 98.46
SYSAUX 95.15
USERS 9.32
UNDOTBS1 3.5
UNDOTBS2 2.93
TEMP
]
# Skip the first two header lines and get an iterator for the rest.
iter = output.each_line.drop(2)
# Iterate through each line with a hash to collect all the stats.
stats = iter.each_with_object({}) { |line,hash|
# Split the line on whitespace.
line.split(/\s+/, 2).each_slice(2) { |k,v|
# Store the key/value pair after stripping the newline and converting to a Float
hash[k] = v.chomp.to_f
}
}
# Now do whatever you want with the resulting Hash of stats.
# {"SYSTEM"=>98.46, "SYSAUX"=>95.15, "USERS"=>9.32, "UNDOTBS1"=>3.5, "UNDOTBS2"=>2.93, "TEMP"=>0.0}
puts "Running out of space" if stats.any? { |_,v| v > 90 }
您可以在Enumerable 模块中找到我使用的大部分方法。
推荐阅读
- java - 如何在 Maven 项目中正确导入 org.w3c.dom?
- angular - 如何在 Angular 5 中验证表单数组中的电子邮件或电话字段?
- jmeter - 如何从响应数据中获取 href URL 中的特定属性值
- visual-studio-2010 - 删除逗号或将逗号更改为空格 SSIS 2010
- c - 没有定义的静态函数声明
- debugging - VS Code – 通过键盘跳转到当前调试位置
- batch-file - 如何删除批处理文件中新生成的文件
- ios - CKError.Code.networkFailure 什么时候会发生?如何解决?
- c++ - 如何调用结构数组来运行?
- cryptography - 混合 Lopez Dahab 仿射坐标中的椭圆曲线点相加算法