Extending the geocoder gem, I am trying to support Ruby version 1.8.7, 1.9.2 and 1.9.3.
扩展地理编码器gem,我试图支持Ruby版本1.8.7,1.9.2和1.9.3。
In 1.9.2 and 1.9.3 everything works fine, but in 1.8.7, when I try to run:
在1.9.2和1.9.3中,一切正常,但在1.8.7中,当我尝试运行时:
hashes.sort_by{ |key, value| value }
it gives me
它给了我
NoMethodError: undefined method `<=>' for nil:NilClass
My hashes
array looks like this:
我的哈希数组看起来像这样:
[
{"u33dc0cpnnf4j6c9vksk7zzp"=>1},
{"u33ddph3wbe2cjnfnxe98sn0"=>1},
{"u33616p4rb8vtm9uscy26f5b"=>1}
]
Looking at the docs, it doesn't seem to be using <=>
anywhere in the source for sort_by
.
查看文档,它似乎没有在source_by的源中的任何地方使用<=>。
What's causing this error?
是什么导致了这个错误?
1 个解决方案
#1
3
Ruby internally uses <=>
to compare while sorting.
Ruby在内部使用<=>进行排序时进行比较。
I think there is a missunderstanding in the block for sort_by
: you get an array element as block argument, not the key/values of the hashes. So value
always is nil
. And while in Ruby >=1.9 nil <=> nil
is zero, there is no <=>
method on nil
for Ruby 1.8.
我认为在sort_by的块中存在一个误解:你得到一个数组元素作为块参数,而不是哈希的键/值。所以价值总是零。而在Ruby> = 1.9 nil <=> nil为零时,Ruby 1.8上的nil没有<=>方法。
So what you have to do is the sort_by
call, for example to something like this:
所以你要做的就是sort_by调用,例如:
hashes = [
{"u33dc0cpnnf4j6c9vksk7zzp"=>1},
{"u33ddph3wbe2cjnfnxe98sn0"=>1},
{"u33616p4rb8vtm9uscy26f5b"=>1}
]
hashes.sort_by { |val| val.values.first }
This sorts by the first value of each hash.
这按每个哈希的第一个值排序。
#1
3
Ruby internally uses <=>
to compare while sorting.
Ruby在内部使用<=>进行排序时进行比较。
I think there is a missunderstanding in the block for sort_by
: you get an array element as block argument, not the key/values of the hashes. So value
always is nil
. And while in Ruby >=1.9 nil <=> nil
is zero, there is no <=>
method on nil
for Ruby 1.8.
我认为在sort_by的块中存在一个误解:你得到一个数组元素作为块参数,而不是哈希的键/值。所以价值总是零。而在Ruby> = 1.9 nil <=> nil为零时,Ruby 1.8上的nil没有<=>方法。
So what you have to do is the sort_by
call, for example to something like this:
所以你要做的就是sort_by调用,例如:
hashes = [
{"u33dc0cpnnf4j6c9vksk7zzp"=>1},
{"u33ddph3wbe2cjnfnxe98sn0"=>1},
{"u33616p4rb8vtm9uscy26f5b"=>1}
]
hashes.sort_by { |val| val.values.first }
This sorts by the first value of each hash.
这按每个哈希的第一个值排序。