Advertisement
nanenj

Ruby example

Jun 25th, 2017
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 2.15 KB | None | 0 0
  1. class Thing
  2.   attr_accessor :location
  3.  
  4.   def initialize(x,y)
  5.     @location = Location.new(x,y)
  6.   end
  7. end
  8.  
  9. class Location
  10.   attr_accessor :x, :y
  11.  
  12.   def initialize(x, y)
  13.     @x = x
  14.     @y = y
  15.   end
  16. end
  17.  
  18. rnd = Random.new
  19. things = [*0..10].map { |x|
  20.   Thing.new(rnd.rand(100), rnd.rand(100))
  21. }
  22.  
  23. puts things.inspect
  24.  
  25. sorted_things = things.each.sort { |a, b| a.location.x <=> b.location.x }
  26.  
  27. puts sorted_things.inspect
  28.  
  29. Sample output:
  30.  
  31. [#<Thing:0x0055f89db51b48 @location=#<Location:0x0055f89db51b20 @x=94, @y=86>>, #<Thing:0x0055f89db51af8 @location=#<Location:0x0055f89db51a58 @x=77, @y=15>>, #<Thing:0x0055f89db51a30 @location=#<Location:0x0055f89db51a08 @x=3, @y=97>>, #<Thing:0x0055f89db519e0 @location=#<Location:0x0055f89db51990 @x=25, @y=5>>, #<Thing:0x0055f89db51968 @location=#<Location:0x0055f89db51940 @x=29, @y=85>>, #<Thing:0x0055f89db51918 @location=#<Location:0x0055f89db518f0 @x=60, @y=48>>, #<Thing:0x0055f89db51878 @location=#<Location:0x0055f89db51800 @x=42, @y=55>>, #<Thing:0x0055f89db517b0 @location=#<Location:0x0055f89db51710 @x=15, @y=61>>, #<Thing:0x0055f89db51698 @location=#<Location:0x0055f89db51670 @x=64, @y=46>>, #<Thing:0x0055f89db51580 @location=#<Location:0x0055f89db514b8 @x=11, @y=71>>, #<Thing:0x0055f89db51468 @location=#<Location:0x0055f89db513c8 @x=70, @y=76>>]
  32. [#<Thing:0x0055f89db51a30 @location=#<Location:0x0055f89db51a08 @x=3, @y=97>>, #<Thing:0x0055f89db51580 @location=#<Location:0x0055f89db514b8 @x=11, @y=71>>, #<Thing:0x0055f89db517b0 @location=#<Location:0x0055f89db51710 @x=15, @y=61>>, #<Thing:0x0055f89db519e0 @location=#<Location:0x0055f89db51990 @x=25, @y=5>>, #<Thing:0x0055f89db51968 @location=#<Location:0x0055f89db51940 @x=29, @y=85>>, #<Thing:0x0055f89db51878 @location=#<Location:0x0055f89db51800 @x=42, @y=55>>, #<Thing:0x0055f89db51918 @location=#<Location:0x0055f89db518f0 @x=60, @y=48>>, #<Thing:0x0055f89db51698 @location=#<Location:0x0055f89db51670 @x=64, @y=46>>, #<Thing:0x0055f89db51468 @location=#<Location:0x0055f89db513c8 @x=70, @y=76>>, #<Thing:0x0055f89db51af8 @location=#<Location:0x0055f89db51a58 @x=77, @y=15>>, #<Thing:0x0055f89db51b48 @location=#<Location:0x0055f89db51b20 @x=94, @y=86>>]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement