2017-02-24 176 views
0

查找文本我有一个代码在阵列红宝石

require 'rubygems' 
conf_array = [] 
File.open("C:/My Program Files/readme.txt", "r").each_line do |line| 
conf_array << line.chop.split("\t") 
end 

a = conf_array.index{|s| s.include?("server =")} 
puts a 

和不显示的项的索引。为什么?

阵列看起来像

conf_array = [ 
    ["# This file can be used to override the default puppet settings."], 
    ["# See the following links for more details on what settings are available:"], 
    ["# - docs.puppetlabs.com/puppet/latest/reference/config_important_settings.html"], 
    ["# - docs.puppetlabs.com/puppet/latest/reference/config_about_settings.html"], 
    ["# - docs.puppetlabs.com/puppet/latest/reference/config_file_main.html"], 
    ["# - docs.puppetlabs.com/references/latest/configuration.html"], ["[main]"], 
    ["server = server.net.pl"], 
    ["splay = true"], 
    ["splaylimit = 1h"], 
    ["wiatforcert = 30m"], 
    ["http_connect_timeout = 2m"], 
    ["http_read_timeout = 30m"], 
    ["runinterval = 6h"], 
    ["waitforcert = 30m"] 
] 

而接下来如何显示该项目?我的意思是a = conf_array[#{a}]表示语法错误。

我也试过

new_array = [] 
new_array = conf_array.select! {|s| s.include?("server =")} 

并再次将其简化版,显示找到的项目。任何建议?

+0

“红宝石” 是一个你标签,因为它应该是。在问题标题中加入“Ruby”是多余的。 –

回答

2

完美使用案例Enumerable#grep

File.open("C:/My Program Files/readme.txt", "r") 
    .each_line 
    # no need to .flat_map { |l| l.split(/\t/) } 
    .grep /server =/ 
#⇒  ["server = server.net.pl"] 
+0

这有效。是否存在阻止查找文本的可能性“sn_server =”? – mila002

+0

'Enumerable#grep'接受一个正则表达式。通过'/^server = /'在行的开始处查找'server'等等。边距太小而无法解释正则表达式如何在细节中工作。 – mudasobwa

+0

在记事本++中,我写的/^server = /不起作用。为什么? – mila002

1

的问题是,你不叫String#include?,但Array#include?

["server = something.pl"].include?('server = ') 
# false 
"server = something.pl".include?('server = ') 
# true 

取出split("\t")

读取该文件到一个数组,你可以使用:

conf_array = File.readlines("C:/My Program Files/readme.txt") 

conf_array = File.readlines("C:/My Program Files/readme.txt").map(&:chomp)