0

나는 지리적 좌표를 저장하는 데 사용하는 location 테이블이 있습니다.BigDecimals를 사용하는 Object가 to_s에 빈 문자열을 반환합니다.

class Location < ActiveRecord::Base 
    # Location has columns/attributes 
    # BigDecimal latitude 
    # BigDecimal longitude 

    (...) 

    def to_s 
    @latitude.to_s << ', ' << @longitude.to_s 
    end 
end 

그러나 위치에서 to_s를 호출하면 BigDecimal이 빈 문자열로 변환됩니다.

ruby > l 
=> #<Location id: 1, latitude: #<BigDecimal:b03edcc,'0.4713577E2',12(12)>, longitude: #<BigDecimal:b03ecb4,'-0.7412786E2',12(12)>, created_at: "2011-08-06 03:41:51", updated_at: "2011-08-06 22:21:48"> 
ruby > l.latitude 
=> #<BigDecimal:b035fb0,'0.4713577E2',12(12)> 
ruby > l.latitude.to_s 
=> "47.13577" 
ruby > l.to_s 
=> ", " 

왜 그런가?

답변

3

귀하의 to_s 구현이 잘못, 그것은이 있어야한다 :

def to_s 
    latitude.to_s << ', ' << longitude.to_s 
end 

액티브 속성은 인스턴스 변수로 동일하지와 객체의 내부 @latitude에 액세스하는 객체의 내부 latitude 접근과 동일하지 않습니다, @latitude이다 인스턴스 변수 인 latitude은 ActiveRecord가 생성하는 메서드에 대한 호출입니다.

nil.to_s << ', ' << nil.to_s 

을하고 당신이 찾고있는 결과되지 않습니다 :

또한, 당신의 to_s 원본 것은 바로이 일을 그래서 인스턴스 변수 처음 사용할 nil로 자동 만듭니다.

관련 문제