[英]Object with BigDecimals returns empty strings on to_s
I have a location
table I use to store geo coordinates: 我有一个用于存储地理坐标的location
表:
class Location < ActiveRecord::Base
# Location has columns/attributes
# BigDecimal latitude
# BigDecimal longitude
(...)
def to_s
@latitude.to_s << ', ' << @longitude.to_s
end
end
However, when I call to_s
on a Location, the BigDecimal
inside converts to an empty string. 但是,当我在Location上调用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
=> ", "
Any idea why? 知道为什么吗?
Your to_s
implementation is wrong, it should be this: 您的to_s
实现是错误的,应该是这样的:
def to_s
latitude.to_s << ', ' << longitude.to_s
end
ActiveRecord attributes are not the same as instance variables and accessing @latitude
inside the object is not the same as accessing latitude
inside the object, @latitude
is an instance variable but latitude
is a call to a method that ActiveRecord creates for you. ActiveRecord属性与实例变量不同,并且在对象内部访问@latitude
与在对象内部访问latitude
并不相同, @latitude
是实例变量,但latitude
是ActiveRecord为您创建的方法的调用。
Also, instance variables auto-create as nil
on first use so your original to_s
was just doing this: 此外,实例变量在首次使用时会自动创建为nil
,因此您原来的to_s
只是在执行以下操作:
nil.to_s << ', ' << nil.to_s
and that isn't the result you're looking for. 那不是您要寻找的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.