开发者

Ordering two separate classes

开发者 https://www.devze.com 2023-03-20 06:32 出处:网络
How would 开发者_Python百科one go about ordering two different classes? So say there\'s Class1 and Class2 that both have the same kind of field, how would I do (Class1 + Class2).asc(:field)?You can do

How would 开发者_Python百科one go about ordering two different classes? So say there's Class1 and Class2 that both have the same kind of field, how would I do (Class1 + Class2).asc(:field)?


You can do this way, for example

 class A
    attr_accessor :f1
 end

 class B
    attr_accessor :f1
 end

 a=A.new
 a.f1="a"

 b=B.new
 b.f1="b"

 arr = []
 arr << b << a
=> [#<B:0x6153e0c0 @f1="b">, #<A:0x55a517bd @f1="a">]

and you can sort by

arr.sort_by(&:f1)
=> [#<A:0x55a517bd @f1="a">, #<B:0x6153e0c0 @f1="b">]

is the short form of

arr.sort_by {|x| x.f1}

even you can use sort method to specify asc,desc

>> arr.sort{|x,y| x.f1 <=> y.f1}
=> [#<A:0x55a517bd @f1="a">, #<B:0x6153e0c0 @f1="b">]
>> arr.sort{|x,y| y.f1 <=> x.f1}
=> [#<B:0x6153e0c0 @f1="b">, #<A:0x55a517bd @f1="a">]

hope this helps

0

精彩评论

暂无评论...
验证码 换一张
取 消