Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Sorting an array with another array [duplicate]

let o1, o2, o3, o4 activerecord objects with

  • o1.kind = "att2"
  • o2.kind = "att3"
  • o3.kind = "att4"
  • o4.kind = "att1"

Let a = [o1, o2, o3, o4]

Let b = ['att1', 'att3', 'att4', 'att2']

I need to sort a with b so that the new order in a becomes:

a = [o4, o2, o3, o1]

I tried

a.sort_by do |element|
  b.index(element)
end

But how to sort by kind?

like image 832
Alex Avatar asked Feb 26 '26 07:02

Alex


2 Answers

You need the index of element.kind, not element.

a.sort_by do |element|
  b.index(element.kind)
end
like image 80
mihai Avatar answered Feb 28 '26 21:02

mihai


O(n+m):

Hash[a.map { |o| [o.kind, o] }].values_at(*b)
like image 36
tokland Avatar answered Feb 28 '26 20:02

tokland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!