作者刚刚接触Ruby,因之前总认为脚本语言语法不规范,对脚本语言有些偏见,如不是项目需要并不会去学习PYTHON、RUBY等语言。现在项目中需要实现对象数组排序的任务,对于昨天开始看ruby的我来说压力山大啊!【汗】
1 #!/usr/bin/ruby
2
3 class Location
4 attr_accessor :longitude
5 attr_accessor :latitude
6 def initialize(lo,la)
7 @longitude, @latitude = lo,la
8 end
9 end
10
11 class OBD
12 attr_accessor :gps
13 attr_accessor :loc
14 def initialize(g,l)
15 @gps = g
16 @loc = l
17 end
18
19 end
20
21 loc = Location.new(10,20)
22 obd = OBD.new(1,loc)
23 loc2 = Location.new(20,30)
24 obd2 = OBD.new(5,loc2)
25 loc3 = Location.new(40,50)
26 obd3 = OBD.new(2,loc3)
27
28 @obds = []
29 @obds[0] = obd
30 @obds[1] = obd2
31 @obds[2] = obd3
32
33
34 @obds.sort! {|a,b| a.gps <=> b.gps}#注意此处的'!',如果没有'!',则原数组不会被改变,建议去掉叹号后试试效果
35 puts obd.gps
36 puts obd.loc.longitude
37 puts obd.loc.latitude
38 puts "#{@obds[0].gps},#{@obds[0].loc.longitude},#{@obds[0].loc.latitude}"
39 puts "#{@obds[1].gps},#{@obds[1].loc.longitude},#{@obds[1].loc.latitude}"
40 puts "#{@obds[2].gps},#{@obds[2].loc.longitude},#{@obds[2].loc.latitude}"