I'm fairly new to Ruby and I'm trying to achieve the following : I have an array of objects with two properties (refers_to and is) which are already sorted by date. On top of that, I want to sort them such as
obj1 < obj2 if obj1.refers_to == obj2.is
This is what I have tried so far, but :
- I'm pretty such that is no the 'Ruby' way of doing it.
It's not even working : Error
undefined methodsort_by' for #<` (I reckon I could have something to do with mutating while enumerating)@array.each_with_index do |e,i| if e.refers_to != 0 @array.slice(i+1,@array.count-i-1).each_with_index do |f,j| if f.is == e.refers_to #@array.insert( ... ) Insert doesn't work end end end end
Update : Majioa's answer
Although I learned a lot from that answer and though it was working while fiddling with a small dataset, I now realize it's not and I'm beginning to think that this result can't be obtained by a (binary) sort algorithm.
My algebra is out of order so I'm going to lack the proper formalism, but basically what the sorting algorithm is doing is comparing the elements two by two and moving them accordingly.
Let's use this example :
4, refers_to =>2
3
2
1
when we reach this state :
3,
2,
4,refers_to =>2
1
At that point, we are going to need that say : if 4 is at the right place, don't move it further, i.e. when comparing '4' to '1', we need to know the state of '2', hence my postulate :
This can't be achieved by a binary sort.
- Do I make sense ?
- Can we make a tertiary sort ?
:sortmethod with block like:arr.sort do |x,y| x <=> y end, and when the result is-1,xhas been put beforey, if1vice versa.obj1.refers_to == obj2.is => trueimplyobj2.refers_to == obj1.is => false?