I am trying to sort string elements in array. Let's say I want to sort it [b, e, f, t, g], but want to keep e in first in ruby. So the result should be [e, b, f, g, t]. How can I write a code in ruby that sort the array that way.
["b", "e", "f", "t", "g"] .sort_by { |s| [s == 'e' ? 0 : 1, s] }
#=> ["e", "b", "f", "g", "t"]
Here Enumerable#sort_by uses Array#<=> to compare each pair of elements computed by the block, such as [0, "e"] and [1, "b"]. See the third paragraph of the doc for Array#<=>.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With