Justin Collins
2/27/2008 10:29:00 PM
Jeff Miller wrote:
> Thanks for the reply!
>
> That does make sense! However, I still can't get this to work properly.
> I tried to use strip and chomp, but both of them kicked me errors
> "undefined method 'chomp' called for nil:NilClass (NoMethodError)". I
> figure this is kind of odd, since I've used both of these in RoR before.
> FYI, the code I posted is the entire script... perhaps I'm missing some
> sort of 'require' statement or something?
>
Ah, good point. That happens on the last loop through, when the file is
empty. My apologies.
> Anyhow, I tried to use the \n, but I can't get to work either... I also
> tried @array[0] == '\n' and a bunch of other little changes. How may I
> construct an IF statement with this?
>
> Thanks again,
> - Jeff
>
Here's a way, with some other changes:
File.open("test.txt", "r") do |file|
while (line = file.gets)
array = line.split(':')
if array[0] == 'cn'
puts array[1]
elsif array[0] == 'title'
puts " Title: #{array[1]}"
elsif array[0] == 'company'
puts " Company: #{array[1]}"
elsif line.strip.empty?
puts "-----"
end
end
end
--------------
File.open do |f| ... end will make sure the file gets closed for you.
Using @array is not necessary, as it just needs to be a local variable, not an instance variable.
String interpolation is not necessary to print an element of the array.
line.strip will get rid of any whitespace and then you can check if the string is empty.
Also, note what happens when you get a line that is neither empty nor matches any of the above.
You can use a series of elsifs to make it slightly shorter/faster/easier to read.
-Justin