V
Vance A Heron
Hello,
I'm having a problem using sort! to sort an array
in which each element is an array. I tried to generate
a short example, and am getting different, but still
puzzling behavior. In my real program, the error I get
is:
Any help understanding this would be appreciated.
Thanks,
Vance
Short example:
---
#! /usr/bin/env ruby
a = [ ["Car", "Drive"], ["Boat", "Sail"], ["Plane", "Fly"] ]
puts "Original Array"
a.each{|v| p v}
puts "\nSort to new array"
b = a.sort{ |a, b| a[0] <=> b[0] }
b.each{|v| puts "class(#{v.class}) #{v[0]}, #{v[1]}"}
puts "\nSort to self"
a.sort!{ |a, b| a[0] <=> b[0] }
a.each{|v| puts "class(#{v.class}) #{v[0]}, #{v[1]}"}
---
Output from run...
SUN:quigon> sortprob.rb
Original Array
["Car", "Drive"]
["Boat", "Sail"]
["Plane", "Fly"]
Sort to new array
class(Array) Boat, Sail
class(Array) Car, Drive
class(Array) Plane, Fly
Sort to self
class(String) 67, 97
I'm having a problem using sort! to sort an array
in which each element is an array. I tried to generate
a short example, and am getting different, but still
puzzling behavior. In my real program, the error I get
is:
bin/newr2r.rb:107:in `sort': comparison of Array with Array failed
(ArgumentError)
Any help understanding this would be appreciated.
Thanks,
Vance
Short example:
---
#! /usr/bin/env ruby
a = [ ["Car", "Drive"], ["Boat", "Sail"], ["Plane", "Fly"] ]
puts "Original Array"
a.each{|v| p v}
puts "\nSort to new array"
b = a.sort{ |a, b| a[0] <=> b[0] }
b.each{|v| puts "class(#{v.class}) #{v[0]}, #{v[1]}"}
puts "\nSort to self"
a.sort!{ |a, b| a[0] <=> b[0] }
a.each{|v| puts "class(#{v.class}) #{v[0]}, #{v[1]}"}
---
Output from run...
SUN:quigon> sortprob.rb
Original Array
["Car", "Drive"]
["Boat", "Sail"]
["Plane", "Fly"]
Sort to new array
class(Array) Boat, Sail
class(Array) Car, Drive
class(Array) Plane, Fly
Sort to self
class(String) 67, 97