为什么是_a? Hash 类返回 false?
为什么 is_a?
对 Hash
类返回 false
?
示例:
value = {"x" => 3, "y" => 2}
puts value.class
puts value.is_a?(Hash)
输出:
Hash
false
我使用 Ruby 1.9.2
更新:我的课程的完整源代码:
class LatLng
include Mongoid::Fields::Serializable
attr_reader :lat, :lng
def serialize(value)
return if value.nil?
puts value.class
puts value.is_a?(Hash)
if value.is_a?(self.class)
puts "is geopoint" + value.to_json
{'lng' => value.lng.to_f, 'lat' => value.lat.to_f}
elsif value.is_a?(Hash)
hash = value.with_indifferent_access
puts "is hash" + value.to_json
{'lng' => hash['lng'].to_f, 'lat' => hash['lat'].to_f}
end
end
def deserialize(value)
return if value.nil?
value.is_a?(self.class) ? value : LatLng.new(value['lat'], value['lng'])
end
def initialize(lat, lng)
@lat, @lng = lat.to_f, lng.to_f
end
def [](arg)
case arg
when "lat"
@lat
when "lng"
@lng
end
end
def to_a
[lng, lat]
end
def ==(other)
other.is_a?(self.class) && other.lat == lat && other.lng == lng
end
end
Why is_a?
returns false
for a Hash
class?
Example:
value = {"x" => 3, "y" => 2}
puts value.class
puts value.is_a?(Hash)
Output:
Hash
false
Im using Ruby 1.9.2
UPDATED: full source of my class:
class LatLng
include Mongoid::Fields::Serializable
attr_reader :lat, :lng
def serialize(value)
return if value.nil?
puts value.class
puts value.is_a?(Hash)
if value.is_a?(self.class)
puts "is geopoint" + value.to_json
{'lng' => value.lng.to_f, 'lat' => value.lat.to_f}
elsif value.is_a?(Hash)
hash = value.with_indifferent_access
puts "is hash" + value.to_json
{'lng' => hash['lng'].to_f, 'lat' => hash['lat'].to_f}
end
end
def deserialize(value)
return if value.nil?
value.is_a?(self.class) ? value : LatLng.new(value['lat'], value['lng'])
end
def initialize(lat, lng)
@lat, @lng = lat.to_f, lng.to_f
end
def [](arg)
case arg
when "lat"
@lat
when "lng"
@lng
end
end
def to_a
[lng, lat]
end
def ==(other)
other.is_a?(self.class) && other.lat == lat && other.lng == lng
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试禁用您已加载的任何gems/扩展,并尝试使用干净的ruby
更新:
尝试
value.is_a?(::Hash)
PS: 尝试阅读有关 Ruby 中的 Duck Typing 的内容。也许您应该调用
value.respond_to?(:key)
而不是value.is_a?(Hash)
try to disable any gems/extensions you have loaded, and try with clean ruby
UPDATE:
try
value.is_a?(::Hash)
PS: try to read about Duck Typing in Ruby. Maybe you should call
value.respond_to?(:key)
instead ofvalue.is_a?(Hash)
当我在 Hash 类之前添加“::”时,它开始工作。
输出:
When I added "::" before Hash class it starts working.
Output:
事实并非如此。
Mongoid
Hash
不是纯 RubyHash
,也不会扩展它。您应该检查实际类型,可能使用输入
。仅仅因为某些内容打印出
Hash
并不意味着 (a) 它是您认为的继承链的一部分,以及 (b) 它是Hash
(见证 ActiveRecordArray
,在某种程度上是谎言)。It doesn't.
A Mongoid
Hash
isn't a pure-RubyHash
, nor does it extend it. You should check the actual type, probably by usingtype
.Just because something prints out
Hash
doesn't mean (a) that it's part of the inheritance chain you think it is, and (b) that it's aHash
(witness ActiveRecordArray
, which lies, to a degree).