객체 속성으로 루비에서 객체 배열을 정렬 하시겠습니까?
Ruby on Rails에 객체 배열이 있습니다. 객체의 속성으로 배열을 정렬하고 싶습니다. 가능합니까?
대신 sort_by를 사용하는 것이 좋습니다.
objects.sort_by {|obj| obj.attribute}
특히 속성이 계산 될 수있는 경우.
또는 더 간결한 접근법 :
objects.sort_by(&:attribute)
예, Array#sort!
이것을 사용 하는 것은 쉽습니다.
myarray.sort! { |a, b| a.attribute <=> b.attribute }
오름차순 :
objects_array.sort! { |a, b| a.attribute <=> b.attribute }
또는
objects_array.sort_by{ |obj| obj.attribute }
내림차순 :
objects_array.sort! { |a, b| b.attribute <=> a.attribute }
또는
objects_array.sort_by{ |obj| obj.attribute }.reverse
첫 번째 속성이 두 번째 속성보다 중요한 두 가지 속성으로 정렬 해야하는 경우 (첫 번째 인수가 동일한 경우에만 두 번째 인수를 고려하는 것을 의미) 다음과 같이 할 수 있습니다
myarray.sort{ |a,b| (a.attr1 == b.attr1) ? a.attr2 <=> b.attr2 : a.attr1 <=> b.attr1 }
또는 배열 배열의 경우
myarray.sort{ |a,b| (a[0] == b[0]) ? a[1] <=> b[1] : a[0] <=> b[0] }
<=> 메소드를 재정 의하여 클래스를 정렬 가능하게 만들 수 있습니다.
class Person
attr_accessor :first_name, :last_name
def initialize(first_name, last_name)
@first_name = first_name
@last_name = last_name
end
def <=>(other)
@last_name + @first_name <=> other.last_name + other.first_name
end
end
이제 Person 객체의 배열은 last_name에서 정렬 가능합니다.
ar = [Person.new("Eric", "Cunningham"), Person.new("Homer", "Allen")]
puts ar # => [ "Eric Cunningham", "Homer Allen"] (Person objects!)
ar.sort!
puts ar # => [ "Homer Allen", "Eric Cunningham" ]
위와 같이 Array # sort가 잘 작동합니다.
myarray.sort! { |a, b| a.attribute <=> b.attribute }
BUT, you need to make sure that the <=>
operator is implemented for that attribute. If it's a Ruby native data type, this isn't a problem. Otherwise, write you own implementation that returns -1 if a < b, 0 if they are equal, and 1 if a > b.
More elegant objects.sort_by(&:attribute)
, you can add on a .reverse
if you need to switch the order.
Yes its possible
http://ariejan.net/2007/01/28/ruby-sort-an-array-of-objects-by-an-attribute/
@model_name.sort! { |a,b| a.attribute <=> b.attribute }
참고URL : https://stackoverflow.com/questions/882070/sorting-an-array-of-objects-in-ruby-by-object-attribute
'development' 카테고리의 다른 글
ViewModel에서 버튼의 가시성을 부울 값에 바인딩 (0) | 2020.07.23 |
---|---|
정규식은 태그 사이의 모든 텍스트를 선택 (0) | 2020.07.23 |
Maven 설치 OSX 오류 지원되지 않는 major.minor 버전 51.0 (0) | 2020.07.23 |
jQuery UI Datepicker를 현지화하려면 어떻게합니까? (0) | 2020.07.23 |
Rails 테스트 스위트에서 단일 테스트를 실행하는 방법은 무엇입니까? (0) | 2020.07.23 |