【问题标题】:Finding text in array Ruby在数组Ruby中查找文本
【发布时间】:2017-07-15 06:20:15
【问题描述】:

我有密码

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

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

【问题讨论】:

  • "ruby" 是您的标签之一,应该如此。问题标题中包含“Ruby”是多余的。

标签: arrays ruby indexing


【解决方案1】:

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"]

【讨论】:

  • 这行得通。是否有任何可能阻止查找文本,例如"sn_server="?
  • Enumerable#grep 接受正则表达式。传递/^server = / 以在行首查找server 等。边距太小,无法详细解释正则表达式的工作原理。
  • 在记事本++中,我在 /^server = / 之后写的任何东西都不起作用。为什么?
  • 好的,我找到了 File.open("C:/My Program Files/readme.txt", "r").each_line.grep(/server =/)
【解决方案2】:

问题是你不叫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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    • 2015-08-19
    • 1970-01-01
    相关资源
    最近更新 更多