Forum: Ruby Re: help regarding extracting a particular value in a file

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
unknown (Guest)
on 2006-05-26 12:28
(Received via mailing list)
Assuming that your data is in a file "data_to_split.txt" in the same
directory,
you can do this:



file_name="data_to_split.txt"
data_array=IO.readlines(file_name)  #  reads content of file into an
Array (
each entry = one  line)
only_second_entries=[]
data_array.each{|line|
only_second_entries<<(line.split(',')[1])  # note that indices start  at
0 in
Ruby
}
p 'only second entries contains'
p  only_second_entries

If you have more complicated patterns that separate your data than just
a
comma,
you can also use split in conjunction with "regular  expressions".

          only_second_entries<<(line.split(/,/)[1])  # note that indices
start  at 0 in Ruby

These "regular expressions" allow to search for things like "a comma and
then two small letters, followed by at least three numbers and then
anything but
"A"", so there is
room for arbitrary complexity ...
Regular expressions are explained in detail here:

_http://www.regular-expressions.info/_
(http://www.regular-expressions.info/)

Best regards,

Axel
Tanushree B. (Guest)
on 2006-05-26 13:02
(Received via mailing list)
Hi Nuralanur

Thanks for your reply and help.
My data.txt file contains data like

p1,p2,p3
c1,c2,c3

I did try your code.Its giving output
p2
c2

but i want to retrieve a single value like p2(2nd value of 1st row ) or
c3
(3rd value of 2nd row)only.

Thanks in advance
Tanushree
This topic is locked and can not be replied to.