I have a ruby array that looks something like this:
my_array = ['mushroom', 'beef', 'fish', 'chicken', 'tofu', 'lamb']
I want to sort the array so that ‘chicken’ and ‘beef’ are the first two items, then the remaining items are sorted alphabetically. How would I go about doing this?
This will create a sorting key for each element of the array, and then sort the array elements by their sorting keys. Since the sorting key is an array, it compares by position, so
[0, 'chicken'] < [1, 'beef'] < [2, 'apple' ] < [2, 'banana'].If you don’t know what elements you wanted sorted to the front until runtime, you can still use this trick: