如果条件满足,如何打印上一个单词?

时间:2016-02-24 22:22:37

标签: ruby-on-rails ruby ruby-on-rails-3

a=[
helloworld:
prodValue:
version:7
class:[
ratio:
value: ""
stackOverflow:
version:3
]
#Inspect Output
"helloworld:"
"prodValue:"
"version:7"    
"class:["
"ratio:"
"value: """
"stackOverflow:"
"version:3"

如果下一个单词是版本,我想打印上一个单词。如果它检测到一些字符串,是否有任何ruby方法来拆分前一个单词?我使用以下ruby脚本

a.delete("\n").delete(":").gsub(/\s+/,'').split('version:',-1)

1 个答案:

答案 0 :(得分:1)

记住上一行,只有符合条件时才输出。

previous_line = ""
File.foreach(input_file) do |line|
   puts previous_line if line.include? 'version:'
   previous_line = line
end

将其存储在数组中:

previous_line = ""
detected_vals = []
File.foreach(input_file) do |line|
   detected_vals << previous_line if line.include? 'version:'
   previous_line = line
end
puts detected_vals.inspect