Ive been looking for awhile now today trying to find a decent example of
this and im really fustrated with it now.
I need to get a specfic section of a line.
lets sat this is the line
example 1 example 2 example 3
I want to get the third section "example 3"so i need to use tab as the
sperater any suggestions?
Even a pointer to a section in the API that might help me would be
usefull
ok but lets say im looping through an array full of different lengths
and layouts of strings for instance
example example example
exmaple/dfsd/asdf/ asdfasdf
example 1 example2 example 3
laskdjflkasdjfkl
im looking to see if the that third string on line 3 is actually there
so passing very line into array and then checking each line
arr = Array.new
i = 0
File.foreach(example.txt) do |line|
arr[i] = line
i += 1
end
arr.each do |item|
if (arr.to_s.split("\t")[2] = “example 3”)
puts “found it”
end
arr = Array.new
i = 0
File.foreach(example.txt) do |line|
  arr[i] = line
  i += 1
end
arr = File.readlines(“example.txt”)
Does the same as the code above, but is far more compact.
arr.each do |item|
if (arr.to_s.split("\t")[2] = “example 3”)
 puts “found it”
end
arr.to_s will give you the whole content of the file. You want to use
item.
arr.map! {|line| line.split("\t")[2]}
arr.each_with_index do |field, i|
if field
puts “Found field #{field} in line #{i}”
else
puts “No third field in line #{i}”
end
end
arr = Array.new
i = 0
File.foreach(example.txt) do |line|
arr[i] = line
i += 1
end
arr.each do |item|
if (arr.to_s.split("\t")[2] = “example 3”)
You have an assignment here which is not what you want here.
puts “found it”
end
This is a very inefficient way of doing things. You don’t need to
store the whole file in an array if you are just interested in the
presence test. Btw, you can even do this:
arr.map! {|line| line.split("\t")[2]}
arr.each_with_index do |field, i|
if field
puts “Found field #{field} in line #{i}”
else
puts “No third field in line #{i}”
end
end
thanks alot!
if i want to check that fields value how do i check it like it prints it
out to the screen but i want to use something like this
if field = “example 3”
puts “Found field #{field} in line #{i}”
end
but its still just spitting out each line
I dont want to print each line that has a third field just the specic
one
flag = "FALSE"
arr = File.readlines(var1)
arr.map! {|line| line.split("\t")[2]}
arr.each_with_index do |line, i|
if /#{var2}/ =~ line
flag = "TRUE"
end
end
if (flag == "TRUE")
puts "SUCCESS: This file " +var1 + " does contain the line"
end
if (flag == "FALSE")
puts "ERROR: This file " +var1 + " does not contain the line"
end
thanks for the help
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.