Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you sort an array in Ruby starting at a specific letter, say letter f?

I have a text array.

text_array = ["bob", "alice", "dave", "carol", "frank", "eve", "jordan", "isaac", "harry", "george"]

text_array = text_array.sort would give us a sorted array.

However, I want a sorted array with f as the first letter for our order, and e as the last.

So the end result should be...

text_array = ["frank", "george", "harry", "isaac", "jordan", "alice", "bob", "carol", "dave", "eve"]

What would be the best way to accomplish this?

like image 365
chris P Avatar asked Dec 19 '22 05:12

chris P


1 Answers

Try this:

result = (text_array.select{ |v| v =~ /^[f-z]/ }.sort + text_array.select{ |v| v =~ /^[a-e]/ }.sort).flatten

It's not the prettiest but it will get the job done.

Edit per comment. Making a more general piece of code:

before = []
after = []
text_array.sort.each do |t|
  if t > term
    after << t
  else
    before << t
  end
end
return (after + before).flatten

This code assumes that term is whatever you want to divide the array. And if an array value equals term, it will be at the end.

like image 167
Ryan K Avatar answered May 18 '23 18:05

Ryan K