Robert Klemme
12/14/2007 8:45:00 AM
2007/12/13, Peter Loftus <loftuz@gmail.com>:
> 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")
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:
ruby -anF\\t -e 'if $F[2] == "example 3"; puts "found"; exit 0; end;
END{ raise "not found"}' your_file
But then you'd probably use (g)awk anyway. :-)
So, going back to Ruby:
File.foreach "file.txt" do |line|
if line.chomp.split(/\t/)[2] == "example 3"
puts "found"
break # or: return or exit
end
end
Probably a bit more efficient:
File.foreach "file.txt" do |line|
if /^(?:[^\t]*\t){2}example 3\t/ =~ line
puts "found"
break # or: return or exit
end
end
Kind regards
robert
--
use.inject do |as, often| as.you_can - without end