Ravi kumar Ravi kumar - 5 months ago 14
Ruby Question

Split and print n th column in ruby

I have a file which contains lines in below format.

{'This.is', 'string_1/test/testing_for/work', '/learn/word_in'}
{'This.is', 'string/test/splitting_for/work', '/learn/word_in'}
{'This.is', 'string_1/test/testing_for/work', '/learn/word_in'}
{'This.is', 'string/test/splitting_for/work', '/learn/word_in'}


I need to split these lines and print only the test-type which is
splitting
,
testing
as you can see in input file(Ex. From first line i need only
testing
as a output) also i want to print test-type of which string length equal to 7 or 8 (don't want to print
splitting
test-type).

In the above I need to get the output of

testing
testing


Already tried something like below which is not provide the result what I expected.

f = File.open("/root/tempfile.txt", "r")
f.each do |ln|
ln.chomp
fr = []
fn = []
fr = ln.split("/")
puts fr[2]
end
f.close

Answer

Input File :

{'This.is', 'string/test/splitting_for/work', '/learn/word_in'}
{'This.is', 'string/test/working_for/work', '/learn/word_in'}
{'This.is', 'string/test/nothing_for/work', '/learn/word_in'}
{'This.is', 'string/test/doing_for/work', '/learn/word_in'}
{'This.is', 'string_1/test/testing_for/work', '/learn/word_in'}

Code :

File.open("test.txt", "r").each do |l| 
  l.chomp
  fr = l.split("/")    
  str = fr[2].split("_").first
  str_len = str.length
  puts str if str_len == 7 || str_len == 8
end

Out Put :

working
nothing
testing
Comments