CSV Error Handling

require ‘CSV’
def pricelookup(my_part_number)

csv = CSV.read('C:\price_lookup.csv', :headers => true)
price = csv.find {|row| row['Part No'] == my_part_number }['Price']

return price

end

Above code works fine as long as partnumber exist in price_lookup.csv
file. If partnumber doesn’t exist it crash my sketchup project. how do I
handle this with out crashing my sketchup project.

In this case it crashes because find returns nil when doesn’t find
my_part_number.

Maybe you could try something like this:

require ‘CSV’

def pricelookup(my_part_number)
csv = CSV.read(‘C:\price_lookup.csv’, :headers => true)
price = csv.find {|row| row[‘Part No’] == my_part_number }
price = price[‘Price’] unless price.nil?
end

But you can pass a lambda to find, which is called when there are no
matches:

require ‘CSV’

def pricelookup(my_part_number)
not_found = lambda {
‘whatever_you_want_to_return_when_there_is_no_match’ }

 csv = CSV.read('C:\price_lookup.csv', :headers => true)
 price = csv.find(not_found) {|row| row['Part No'] == my_part_number
 }

end

Also take into account that methods in ruby return the last evaluated
expression, so
in this case you don’t need to return the value explicitly.


Manu C.
[email protected]