首页 > 解决方案 > 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>'

标签: ruby

解决方案


一旦我们得到查询的输出,这就是一个简单的解析问题。

在这里,我使用字符串模拟了输出,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 模块中找到我使用的大部分方法。


推荐阅读