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

前端 未结 3 920
南笙
南笙 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:35

    Array#sort_by is what you're after.

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

    More scalable version in response to comment:

    a=["one", "two", "three"]
    b=["two", "one", "three"]
    
    lookup = {}
    b.each_with_index do |item, index|
      lookup[item] = index
    end
    
    a.sort_by do |item|
      lookup.fetch(item)
    end
    

提交回复
热议问题