2017-02-24 195 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)