Object array sorting in Ruby and Ruby object array sorting

Source: Internet
Author: User

Object array sorting in Ruby and Ruby object array sorting

Sorting of Ruby object arrays

The author has just come into contact with Ruby, because he previously thought that the script language syntax is not standardized and he is somewhat biased against the script language. For example, he does not need to learn PYTHON, RUBY, and other languages because it is not required by the project. Now, the task of sorting object arrays is required in the project. For me who started to look at ruby yesterday, the pressure is huge! [Khan]

However, after some data queries, I finally achieved my desired results. Now I have recorded my own test program to remember the first big bang on the ruby road! The Code is as follows:

1 #! /Usr/bin/ruby 2 3 class Location 4 attr_accessor: longpolling 5 attr_accessor: latitude 6 def initialize (lo, la) 7 @ longpolling, @ latitude = lo, la 8 end 9 end10 11 class OBD12 attr_accessor: gps13 attr_accessor: loc14 def initialize (g, l) 15 @ gps = g16 @ loc = l17 end18 19 end20 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 (4 0, 50) 26 obd3 = OBD. new (2, loc3) 27 28 @ obds = [] 29 @ obds [0] = obd30 @ obds [1] = obd231 @ obds [2] = obd332 33 34 @ obds. sort! {| A, B | a. gps <=> B. gps} # note '! ', If not '! ', Then the original array will not be changed. We recommend that you remove the exclamation point and try the effect 35 puts obd. gps36 puts obd. loc. longitude37 puts obd. loc. latitude38 puts "# {@ obds [0]. gps}, # {@ obds [0]. loc. longpolling}, # {@ obds [0]. loc. latitude} "39 puts" # {@ obds [1]. gps}, # {@ obds [1]. loc. longpolling}, # {@ obds [1]. loc. latitude} "40 puts" # {@ obds [2]. gps}, # {@ obds [2]. loc. longpolling}, # {@ obds [2]. loc. latitude }"

Program running result:

Hope to help you!

[Note]:This article is original by the author.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.