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"
eg 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.
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
stealing
copying 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"]
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.