I want to sort after combining JSON arrays in Ruby.

Asked 2 years ago, Updated 2 years ago, 119 views

Ruby combined the two JSON arrays a, b with the + operator to create an array called c=a+b.
After that, I want to sort c by the key value "id", but it doesn't sort well

.

I will write down what I tried and the results below, so I would appreciate it if you could let me know if you know.

Tried

a=[{id:10000, name:"aaa"}, {id:15000, name:"zzz"}]
b=[{id:12000, name:"bbb"}, {id:20000, name:"yyy"}]

c=a+b
=>[{:id=>10000,:name=>"aaa"}, {:id=>15000,:name=>"zzz"}, {:id=>12000,:name=>"bbb"}, {:id=>20000,:name=>yyyyyyy} }]

c. sort_by {|a|a["id"]}.reverse
=>[{:id=>20000,:name=>"yyy"}, {:id=>12000,:name=>"bbb"}, {:id=>15000,:name=>"zzz"}, {:id=>10000,:name=>"aaa"}]

=======

↓ 本当I really want it sorted like this よう
[{:id=>20000,:name=>"yyy"}, {:id=>15000,:name=>"zzz"}, {:id=>12000,:name=>"bbb"}}{:id=>10000,:name=>"aaaaa"}]

ruby json

2022-09-30 21:44

1 Answers

Symbol looks like an array of Hash keys.Therefore, a["id"] does not seem to be able to sort a[:id] because it does not get the value of a[:id].

a={id:10000, name:"aaa"}
# =>{:id=>10000,:name=>"aaa"}
a ["id"]
# =>nil
a [:id]
# = > 10000

Why don't you change the block you pass to sort_by like this?

c.sort_by {|a|a[:id]}.reverse


2022-09-30 21:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.