0

I have a code

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

and it doesn't display the index of item. Why?

Array looks like

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

And next how to display that item? I mean a = conf_array[#{a}] says syntax error.

I tried also

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

and it again does't display found item. Any suggestion?

1
  • "ruby" is one of your tags, as it should be. It's redundant to have "Ruby" in the question's title. Commented Feb 24, 2017 at 16:31

2 Answers 2

2

Perfect use case for 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"]
Sign up to request clarification or add additional context in comments.

4 Comments

That works. Is there any posisbility to prevent finding text e.g. "sn_server ="?
Enumerable#grep accepts a regular expression. Pass /^server = / to lookup for server in the beginning of the line etc. The margins are too small to explain how regexps work in details.
In notepad++ anything I write after /^server = / doesn't work. Why?
OK, I found File.open("C:/My Program Files/readme.txt", "r").each_line.grep(/server =/)
1

The problem is that you don't call String#include?, but Array#include? :

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

Remove the split("\t").

To read the file into an array, you can just use :

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

or

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.