Read from file to array and stop if ":" found in ruby

How can I in Ruby read a line from a file to 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 greatly appreciated =)

For instance:

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) 

It should read only the following and be contained in an array:

 10.199.198.10 10.199.198.12 10.199.198.13 
+4
source share
1 answer

This is a pretty trivial issue using String#split :

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

Conclusion:

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

String#split splits the string into the specified delimiter and returns an array; therefore line.split(':')[0] accepts the first element of this generated array.

If it has a string without : String#split will return an array with a single element, which is the entire string. Therefore, if you need to do some more error checking, you can 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 separator lines to the result array if the line contains the character :

+13
source

Source: https://habr.com/ru/post/1307771/


All Articles