From 754ee1b4c4ca5027233b4ae3b2aefd486e458e62 Mon Sep 17 00:00:00 2001 From: Harald Eilertsen Date: Sun, 1 Feb 2015 17:41:13 +0100 Subject: Return `nil` if postcodes don't match exactly. --- lib/norwegian-postcodes.rb | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) (limited to 'lib') diff --git a/lib/norwegian-postcodes.rb b/lib/norwegian-postcodes.rb index cc3cd31..be77c8e 100644 --- a/lib/norwegian-postcodes.rb +++ b/lib/norwegian-postcodes.rb @@ -40,26 +40,31 @@ module PostCodes [code, PostCodes.county(code)] end - def >=(postcode) - @postcode.to_i >= postcode.to_i - end - def to_s [@postcode, @city, @municipality, @municipality_name, @cat].join("\t") end end class << self - def load(f) + def load(file) @postcodes = [] - IO.foreach(f, :encoding => Encoding::ISO_8859_15) do |l| + if file.is_a?(String) + f = File.open(file, :encoding => Encoding::ISO_8859_15) + else + f = file + end + + f.each_line do |l| a = l.chomp().split("\t").map{|s| s.encode(Encoding::UTF_8)} @postcodes << PostCode.new(*a) end end def search(pc) - @postcodes.bsearch {|x| x >= pc} + res = @postcodes.bsearch {|x| x.postcode.to_i >= pc.to_i} + unless res.nil? + res.postcode.to_i == pc.to_i ? res : nil + end end def county(c) -- cgit v1.2.3