File Output Problem

A

aidy

Hi,

I am reading a txt file, e.g.

;Country Depot EmployeeID FirstName LastName UserID
null BERLIN G744ahe null Rutter 123

This is the code:

def enter_employees()
f = File.new('c:\employee_data.txt')
f.each do |line|
if !line.include? ";"
data = line.chomp.split(' ')
i = 0
while i < data.length do
if data != "null" or data != nil
puts "i = #{i}"
puts data
i += 1
end
end
end
end
end
enter_employees()

I am trying not to print to the console if data == "null", however
this is the output

i = 0
null
i = 1
BERLIN
i = 2
G744ah
i = 3
null
i = 4
Rutter
i = 5
123

Could someone tell me what I am doing wrong?

Thanks

Aidy
 
C

ChrisH

This line:
if data != "null" or data != nil
should be
if data != "null" and data != nil

In the first case when data=="null" than data != nill so the
statement is True, and likewise if data==nil than data != "null"
and the statement is again True
 
L

lloyd

you could also use:

unless data =="null" or data == nil
puts "i = #{i}"
puts data

some people make better sense using unless because the logic isnt
negated and reads more logically. personally i have no preference but
it may work for you
 
A

aidy

Not so sure whether you are supposed to say thanks on the list; but
thanks for the help and ideas.

Aidy
 
C

ChrisH

Here's how I'd write it:

def enter_employees()
File.open('employee_data.txt','r'){|f| #use block so file is
automatically closed
f.each_line { |line|
next if /^;/ =~ line #check for ';' at start of line
i = 0
line.chomp.split(' ').each{|x|
next if x.nil? or x == "null" #skip nil or "null" values
puts "i = #{i}", x
i += 1
}
}
}
end

Cheers
Chris
 
R

Robert Klemme

aidy said:
Hi,

I am reading a txt file, e.g.

;Country Depot EmployeeID FirstName LastName UserID
null BERLIN G744ahe null Rutter 123

This is the code:

def enter_employees()
f = File.new('c:\employee_data.txt')
f.each do |line|
if !line.include? ";"
data = line.chomp.split(' ')
i = 0
while i < data.length do
if data != "null" or data != nil
puts "i = #{i}"
puts data
i += 1
end
end
end
end
end
enter_employees()

I am trying not to print to the console if data == "null", however
this is the output

i = 0
null
i = 1
BERLIN
i = 2
G744ah
i = 3
null
i = 4
Rutter
i = 5
123

Could someone tell me what I am doing wrong?

Thanks

Aidy


Dunno whether this is what you want...

17:21:54 [Temp]: cat dat
;Country Depot EmployeeID FirstName LastName UserID
null BERLIN G744ahe null Rutter 123
17:22:00 [Temp]: ruby -naF\\s+ -e '/^;/ =~ $_ or puts $F.reject {|x|
"null"==x}' dat
BERLIN
G744ahe
Rutter
123

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,296
Messages
2,571,535
Members
48,281
Latest member
DaneLxa72

Latest Threads

Top