Object with BigDecimals returns empty strings on to_s

倾然丶 夕夏残阳落幕 提交于 2019-12-13 06:06:45

问题


I have a location table I use to store geo coordinates:

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.

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?


回答1:


Your to_s implementation is wrong, it should be this:

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.

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

and that isn't the result you're looking for.



来源:https://stackoverflow.com/questions/6970645/object-with-bigdecimals-returns-empty-strings-on-to-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!