具有BigDecimals的对象在to_s上返回空字符串

时间:2022-09-25 18:26:22

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.

但是,当我在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?

知道为什么吗?

1 个解决方案

#1


3  

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与访问对象内部的纬度不同,@ width是实例变量,但纬度是对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.

这不是你要找的结果。

#1


3  

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与访问对象内部的纬度不同,@ width是实例变量,但纬度是对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.

这不是你要找的结果。