Em Sta
Em Sta

Reputation: 1706

How to avoid undefined method error for Nilclass

I use the dbf gem to read data out of an df file. I wrote some code:

    # encoding: UTF-8
    require 'dbf'
    widgets = DBF::Table.new("patient.dbf")
      widgets.each do |record|
       puts record.vorname
      end

Basically the code works but after ruby writes about 400 record.vorname to the console i get this error:

  ...
  Gisela
  G?nter
  mycode.rb:5:in `block in <main>': undefined method `vorname' for nil:NilClass (NoM
  ethodError)
    from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/dbf-2.0.6/lib/
    dbf/table.rb:101:in `block in each'
    ......

My question is how can i avoid this error? Therefore it would be intresting why ( how you can see in the error) the record.vorname's with ä,ö,ü are displayed like ?,?,? for eg:

Günter is transformed to G?nter

Thanks

Upvotes: 1

Views: 467

Answers (3)

Paulo Fidalgo
Paulo Fidalgo

Reputation: 22331

About your question about the wrong chars, according to the dfb documentation:

Encodings (Code Pages)

dBase supports encoding non-english characters in different formats. Unfortunately, the format used is not always set, so you may have to specify it manually. For example, you have a DBF file from Russia and you are getting bad data. Try using the 'Russion OEM' encoding:

table = DBF::Table.new('dbf/books.dbf', nil, 'cp866')

See doc/supported_encodings.csv for a full list of supported encodings.

So make sure you use the right encoding to read from the DB.

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230551

For some reason, your DBF driver returns nil records. You can pretend that this problem doesn't exist by skipping those.

widgets.each do |record|
  puts record.vorname if record
end

Upvotes: 2

Aaditi Jain
Aaditi Jain

Reputation: 7027

To avoid the NoMethodError for nil:Nil Class you can probably try this:

require 'dbf'
widgets = DBF::Table.new("patient.dbf")
  widgets.each do |record|
   puts record.vorname unless record.blank?
  end

Upvotes: 0

Related Questions