Building your own string sorting method

  • Thread starter Joseph L. Casale
  • Start date
J

Joseph L. Casale

I am trying to find examples of this to help me but can't seem to locate an=
y on the web. Anyone know of any online examples? I know ruby has a built i=
n method for sorting an array, but it's part of a tutorial...

Thanks!
jlc
 
C

Christopher Swasey

I am trying to find examples of this to help me but can't seem to locate any on the web. Anyone know of any online examples? I know ruby has a built in method for sorting an array, but it's part of a tutorial...

A simple example would be a natural order comparison ("a20" sorting
before "a120"). A bit of googling turned up Alan Davies' String#natcmp
implementation:

http://sourcefrog.net/projects/natsort/natcmp.rb

Christopher
 
D

Daniel Finnie

A basic string sorting routine would just sort based on ASCII
codepoints (see a list at http://urltea.com/2tu7 ).

So you could do this in Ruby 1.9:

irb(main):002:0> class String
irb(main):003:1> def <=> other
irb(main):004:2> self.each_char.map(&:eek:rd) <=> other.each_char.map(&:eek:rd)
irb(main):005:2> end
irb(main):006:1> end

<, >, ==, !=, etc. are all defined in terms of <=>, the spaceship
operator, so all of the previous operations are affected when we
define <=>. Arrays sort by comparing the first non-matching element.

irb(main):011:0> %w[a c b g h j g p q].sort
=> ["a", "b", "c", "g", "g", "h", "j", "p", "q"]

Of course this has a lot of deficiencies:

irb(main):014:0> %w[a c b g h j g p q Z A G].sort
=> ["A", "G", "Z", "a", "b", "c", "g", "g", "h", "j", "p", "q"]

So we could downcase each character or something.

But even advanced sorting algorithms have problems -- German sorts
beta as nn or something and lots of other languages have similar
issues. Book listings generally don't include words like "the" when
sorting, etc. I would decide those before starting.
 
J

Joseph L. Casale

locate any on the web. Anyone know of any online examples? I know ruby
has a built in method for sorting an array, but it's part of a
tutorial...

A simple example would be a natural order comparison ("a20" sorting
before "a120"). A bit of googling turned up Alan Davies' String#natcmp
implementation:

http://sourcefrog.net/projects/natsort/natcmp.rb

Christopher

Hi Christopher and Daniel,
You'll have to bear with me as I have just started learning Ruby and both e=
xamples seem a bit over my head as of yet. Is there anything more basic you=
know of?

Thanks for being patient :)
jlc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top