ruby 中的数组排序语法
这是一个非常基本的问题,但我在理解 Ruby 哈希排序方法时遇到了一些困难。
基本上发生的事情是我收到一个无法将字符串转换为整数的消息,所以我的第一个猜测是我正在按字符串(实际上是一个数字)对数组进行排序。该数组包含哈希值,我试图按我用键标识的哈希值之一对其进行排序。
以下是我对数组进行排序的方式:
@receivedArray =(params[:respElementDatas])
puts @receivedArray.class #Its definitely an array
@sortedArray = @receivedArray.sort_by{|ed| ed["element_type_id"]}
我收到的错误是无法在排序行上将字符串转换为整数。
我自然认为这
只是一个简单的问题。 我是否正确地说“ed”是存储在数组中的对象并且我正确引用了它?还有关于如何修复它的任何指示吗?
This is a very basic question but I'm having a bit of trouble understanding Rubys hash sort method.
Basically whats happening is I'm receiving a cannot convert string to integer so my first guess is I'm sorting the array by a string (which is actually a number). The array contains hashes and I'm trying to sort it by one of the hashes values that I've identified with a key.
Heres how I'm sorting my array:
@receivedArray =(params[:respElementDatas])
puts @receivedArray.class #Its definitely an array
@sortedArray = @receivedArray.sort_by{|ed| ed["element_type_id"]}
The error I'm getting is can't convert String into Integer on the sort line.
Naturally I assumed that
Just a quick question.
Am i right in saying that 'ed' is an object that is stored in the array and I'm referencing it correctly? Also any pointers on how to fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的
@receivedArray
是一组数组,或者其中至少有一个数组。例如:Your
@receivedArray
is an array of arrays or has at least one array in it. For example:尝试
ed["element_type_id"].to_i
try
ed["element_type_id"].to_i
您说“ed”是存储在数组中的对象是对的。
如果数组中的所有元素都是哈希值,那么您是否正确引用了它?
一些哈希值的 element_type_id 为字符串,另一些则为整数。
我会检查您在哪里混合 element_type_id 的数据。
您可以尝试
ed["element_type_id"].to_i
,它对于整数没有效果,但对于字符串会将其解析为整数。You are right in saying that 'ed' is an object that is stored in the array.
If all the elements in the array are hashes then you are referencing it correctly?
Some of the hashes have a String and others have an Integer for the element_type_id.
I'd check where you are mixing the data for the element_type_id.
You could try
ed["element_type_id"].to_i
which for an integer will have no effect, but for a string will parse it into an integer.看起来您的错误是说
ed
是一个Array
,而不是Hash
。它可能是一个对的数组:[['key1', 'value1'], ['key2', 'value2']]
,在这种情况下,您需要将代码更改为: rubyprince 建议,查看 p @receivedArray 的输出将有助于澄清这一点。
It looks like your error is saying that
ed
is anArray
, not aHash
. It may be an array of pairs:[['key1', 'value1'], ['key2', 'value2']]
, in which case you would want to change your code to:As rubyprince suggested, seeing the output of
p @receivedArray
would help clarify this.