开发者

Sorting Ruby Arrays - failed with TypeError: can't convert Symbol into Integer

I am trying to sort an array that contains hashes. The array looks something like.

[:amazon, [{:price=>"  396 开发者_JAVA技巧", :author=>"Motwani", :name=>"Randomized Algorithms ", :url=>"", :source=>"amazon"}, 
           {:price=>"  255 ", :author=>"Thomas H. Cormen", :name=>"Introduction To Algorithms ", :url=>"", :source=>"amazon"}]]

I am trying to sort this array using:

source_array.sort_by { |p| p[1][:price] }

But I keep on getting error:

failed with TypeError: can't convert Symbol into Integer

Not sure what indexing is going wrong here


You're trying to sort an array of two elements:

  • hash :amazon,
  • inner big array.

So, any sort call on top array will try to sort these two elements.

What are you trying to achieve could be done this way:

a[1] = a[1].sort_by {|f| f[:price].to_i}

Edit: for a more general approach:

# declare source array
a  = [:amazon, 
[{:price=>"  396 ", :author=>"Motwani", :name=>"Randomized Algorithms ", :url=>"", :source=>"amazon"}, 
{:price=>"  255 ", :author=>"Thomas H. Cormen", :name=>"Introduction To Algorithms ", :url=>"", :source=>"amazon"}]]

# convert to hash for easier processing
b = Hash[*a]

# now sort former inner table by price
b.merge!(b) {|k, v|  v.sort_by {|p| p[:price].to_i}}

# return to old representation
b.to_a[0]
=> [:amazon, [{:price=>"  255 ", :author=>"Thomas H. Cormen", :name=>"Introducti
on To Algorithms ", :url=>"", :source=>"amazon"}, {:price=>"  396 ", :author=>"M
otwani", :name=>"Randomized Algorithms ", :url=>"", :source=>"amazon"}]]


Your input is actually a pair (name, [book]), so make sure you only sort the second element of the pair (the books array):

[source_array[0], source_array[1].sort_by { |book| book[:price].to_i }]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜