Làm thế nào về việc sử dụng một biểu thức chính quy? Ví dụ:
def latlong(dms_pair)
match = dms_pair.match(/(\d\d)º (\d\d)' (\d\d)'' (\d\d)º (\d\d)' (\d\d)''/)
latitude = match[1].to_f + match[2].to_f/60 + match[3].to_f/3600
longitude = match[4].to_f + match[5].to_f/60 + match[6].to_f/3600
{:latitude=>latitude, :longitude=>longitude}
end
Dưới đây là một phiên bản phức tạp hơn mà phản ứng với tọa độ tiêu cực:
def dms_to_degrees(d, m, s)
degrees = d
fractional = m/60 + s/3600
if d > 0
degrees + fractional
else
degrees - fractional
end
end
def latlong(dms_pair)
match = dms_pair.match(/(-?\d+)º (\d+)' (\d+)'' (-?\d+)º (\d+)' (\d+)''/)
latitude = dms_to_degrees(*match[1..3].map {|x| x.to_f})
longitude = dms_to_degrees(*match[4..6].map {|x| x.to_f})
{:latitude=>latitude, :longitude=>longitude}
end
Nguồn
2009-08-22 22:38:41
Cảm ơn! Tôi sẽ chấp nhận câu trả lời thanh lịch này! Tuy nhiên, tôi đã mong đợi một số loại thư viện có thể phân tích các định dạng hoặc biến thể khác. Một chút tinh chỉnh trên regexp sẽ làm! Cám ơn bạn một lần nữa! – rubenfonseca