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…
Thanks!
jlc
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…
Thanks!
jlc
On 3/2/08, Joseph L. Casale [email protected] wrote:
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
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(&:ord) <=>
other.each_char.map(&:ord)
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.
On Sun, Mar 2, 2008 at 5:50 PM, Joseph L. Casale
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 examples seem a bit over my head as of yet. Is there anything more
basic you know of?
Thanks for being patient
jlc
Hey jlc,
try this here: https://github.com/reiz/naturalsorter
That is a very easy to use wrapper for natcmp.rb.
If you still have questions, don’t be shy!
Joseph L. Casale wrote in post #640701:
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 examples seem a bit over my head as of yet. Is there anything more
basic you know of?Thanks for being patient
jlc
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs