How to sort an array in Ruby to a particular order?

前端 未结 3 916
南笙
南笙 2020-12-01 07:56

I want to sort an array in particular order given in another array.

EX: consider an array

a=[\"one\", \"two\", \"three\"]
b=[\"two\", \"one\", \"thr         


        
3条回答
  •  再見小時候
    2020-12-01 08:23

    Assuming a is to be sorted with respect to order of elements in b

    sorted_a = 
    a.sort do |e1, e2|
      b.index(e1) <=> b.index(e2)
    end
    

    I normally use this to sort error messages in ActiveRecord in the order of appearance of fields on the form.

提交回复
热议问题