ruby - sort an array of ranges -


how sort array of ranges

ranges = [range.new(0, 3, true), range.new(3, 5, true), range.new(5, 7, true), range.new(7, 9, true), range.new(9, 11, true), range.new(11, 100, true)] ranges.sort => argumenterror: comparison of range range failed (irb):7:in `sort' (irb):7 /users/praveena/.rvm/rubies/ruby-2.0.0-p247/bin/irb:16:in `<main>' 

but when try

2.0.0p247 :022 > (3...4) <=> (4...8) => nil 2.0.0p247 :023 > (3...4) <=> (1...2) => nil 

am missing ?

it seems range have implementation <=>, not complete. lets check:

> range.new(3,4) <=> range.new(3,4) => 0 # seems correctly identify when 2 equals  > range.new(3,4) <=> range.new(4,4) => nil # seems fails fail when both different! 

this method defined in range because defined on object class(!!!), every object has method defined, doesn't means works. implementation range default one. lets check this:

# lets define dummy class class end => nil  # , create object = a.new => #<a:0x9b1d998>  # can correctly identify when equal <=> => 0  # invalid answer when not equal! <=> 1 => nil 

at point, should understand happening in code.

it totally understandable range not have canonical <=> method because there no mathematical definition greater range (that know), neither common sense definition.


Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -