在数组Ruby中查找文本

时间:2017-02-24 12:08:37

标签: arrays ruby indexing

我有一个代码

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 =")}

并且它再次显示找不到的项目。有什么建议吗?

2 个答案:

答案 0 :(得分: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"]

答案 1 :(得分: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)