From: "Peña, Botp" Date: 2007-06-28T19:43:00+09:00 Subject: Re: Array Problem, sort Array From: F. Senault [mailto:fred@lacave.net] : # Le 28 juin � 06:17, Pe�a, Botp a �crit : # > solution: a) convert elements to some common class (string # is common) # > b) filter those you don't want sorted (using # compact/reject/..) # > or select those you want (using select/map/..) # # c) Use a sort(_by) block (maybe that's what you meant in a) : # >> ["a", nil, "b"].sort_by { |e| (e.nil? ? 'z' : e) } # => ["a", "b", nil] yap, they're all the same, string comparison. another stupid sample below. the comparison is in integers, indirectly handled by array#index. shelf_order = [nil, "orange","spices","apple","peaches", "herbs"] tobe_ordered = ["herbs", "orange","apple",nil,"peaches"] tobe_ordered.sort_by do |e| shelf_order.index(e) end => [nil, "orange", "apple", "peaches", "herbs"] # > A little digression for everyone though... # > irb(main):013:0> [nil].sort # > => [nil] # > # > is that intended? # # Well, you don't need the comparison operator where there's only one # element, do you ? careful with the "one" there. The array returned may be complex. eg, irb(main):029:0> [[nil,[nil,"a"]]].sort => [[nil, [nil, "a"]]] irb(main):030:0> [[nil,[nil,"a"]]].flatten.sort NoMethodError: undefined method `<=>' for nil:NilClass from (irb):30:in `sort' again, as i've said to Phrogz, the behavior hints that nil elements by themselves are sortable. Remember, programs contain blackboxes wc may be complex and not obvious, eg complex_proc_ret_array.sort_complex.foo_proc.bar_proc one could argue bluntly too, eg [nil].sort =>[nil] # yes, there is no need to sort [nil,nil].sort =>[nil,nil] # yes, there is no need to sort I really value consistency of object behavior when it comes to ruby, maybe because it's too dynamic and i want least number of surprises (especially when you chain things). Anyway, I've overlooked this behavior and now I'll have to recheck again my testcases ;) thanks Senault and Phrogz, and kind regards -botp