John Athayde
John Athayde

Reputation: 600

How do I sort_by in Ruby without the initial prepopsition (a, the, etc)

I have a series of manufacturers and some of them use "The" at the beginning of their official name. People refer to them by the actual name, and looking in a select for the name under "M" but it's under "T"

e.g. The Moritz Embroidery Company

I was looking at taking each name, converting it to an array with .split(" ") and dropping "the" (.delete("The")) and then joining again, and THEN sorting, but that just seems the wrong way to do this.

Upvotes: 1

Views: 78

Answers (2)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230326

I was looking at taking each name, converting it to an array with .split(" ") and dropping "the" (.delete("The")) and then joining again, and THEN sorting, but that just seems the wrong way to do this.

This is called the Schwartzian transform and it is what powers ruby's sort_by.

(shamelessly stealingcopying some of @mudasobwa's code)

 input = ["The Moritz", "A Moritz", "The Embroidery Company"]
 input.sort # => naive sort, ["A Moritz", "The Embroidery Company", "The Moritz"]
 input.sort_by { |str| str.gsub(/\A(The|A)\s+/, '') } # sort without prepositions
 # => ["The Embroidery Company", "The Moritz", "A Moritz"]

Upvotes: 5

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Use String#gsub with explicitly defined \A anchor for the matches at the beginning of string only:

input = ["The Moritz", "Not The Embroidery Company"]
input.map { |str| str.gsub(/\AThe\s+/, '') }
#⇒ ["Moritz", "Not The Embroidery Company"]

One-liner for sorting inplace:

input.sort_by { |str| str.gsub!(/\AThe\s+/, '').to_s }
#⇒ ["Moritz", "Not The Embroidery Company"]

Please note, that the latter mutates an original array.

Upvotes: 3

Related Questions