views:

150

answers:

1

Hi! How can I in Ruby read a string from a file into an array and only read and save in the array until I get a certain marker such as ":" and stop reading?

Any help would be much appreciated =)

For example:

10.199.198.10:111  test/testing/testing  (EST-08532522)
10.199.198.12:111  test/testing/testing  (EST-08532522)
10.199.198.13:111  test/testing/testing  (EST-08532522)

Should only read the following and be contained in the array:

10.199.198.10
10.199.198.12
10.199.198.13
+5  A: 

This is a rather trivial problem, using String#split:

results = open('a.txt').map { |line| line.split(':')[0] }

p results

Output:

["10.199.198.10", "10.199.198.12", "10.199.198.13"]

String#split breaks a string at the specified delimiter and returns an array; so line.split(':')[0] takes the first element of that generated array.

In the event that there is a line without a : in it, String#split will return an array with a single element that is the whole line. So if you need to do a little more error checking, you could write something like this:

results = []

open('a.txt').each do |line|
  results << line.split(':')[0] if line.include? ':'
end

p results

which will only add split lines to the results array if the line has a : character in it.

Mark Rushakoff