È possibile utilizzare Enumerable#sort_by
utilizzando un array per mantenere i gruppi desiderati e l'ordinamento per nome senza perdere quei gruppi. Per esempio:
[[0,0,1], [1,1,1], [0,1,0], [1,0,0], [0,1,1]].sort_by &:itself
# => [[0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 1, 1]]
Con questo, è possibile impostare un array con lunghezza 2. Utilizzando l'indice 0 al "gruppo" dagli elementi che si desidera e indice 1 per ordinare per nome.
OR = "OR"
AND = "AND"
_NOT_PRESENT = "_NOT_PRESENT"
array_group = [
{ operator: OR, name: "z string", status: false },
{ operator: AND, name: "a string", status: false },
{ operator: AND, name: "z string", status: true },
{ operator: OR, name: "a string", status: true },
{ operator: _NOT_PRESENT, name: "d string", status: true },
{ operator: _NOT_PRESENT, name: "b string", status: true },
{ operator: _NOT_PRESENT, name: "c string", status: false },
{ operator: _NOT_PRESENT, name: "a string", status: false }
]
# Types of "groups" you want to keep. Greater values will be at the end
BY_NOT_PRESENT = 2
BY_STATUS_FALSE = 1
BY_STATUS_TRUE = 0
array_group.sort_by do |a|
group = if a[:operator] == _NOT_PRESENT
BY_NOT_PRESENT
else
a[:status] ? BY_STATUS_TRUE : BY_STATUS_FALSE
end
[group, a[:name]]
end
#=> [{:operator=>"OR", :name=>"a string", :status=>true},
# {:operator=>"AND", :name=>"z string", :status=>true},
# {:operator=>"AND", :name=>"a string", :status=>false},
# {:operator=>"OR", :name=>"z string", :status=>false},
# {:operator=>"_NOT_PRESENT", :name=>"a string", :status=>false},
# {:operator=>"_NOT_PRESENT", :name=>"b string", :status=>true},
# {:operator=>"_NOT_PRESENT", :name=>"c string", :status=>false},
# {:operator=>"_NOT_PRESENT", :name=>"d string", :status=>true}]
che sto facendo in questo modo, perché se solo sort_by una matrice come [status, not_present, name]
poi status
avrà la precedenza sul tipo, ignorando il name
sorta, risultando in questo modo:
#=> [{:operator=>"OR", :name=>"a string", :status=>true},
# {:operator=>"AND", :name=>"z string", :status=>true},
# {:operator=>"AND", :name=>"a string", :status=>false},
# {:operator=>"OR", :name=>"z string", :status=>false},
# {:operator=>"_NOT_PRESENT", :name=>"b string", :status=>true},
# {:operator=>"_NOT_PRESENT", :name=>"d string", :status=>true},
# {:operator=>"_NOT_PRESENT", :name=>"a string", :status=>false},
# {:operator=>"_NOT_PRESENT", :name=>"c string", :status=>false}]
La dichiarazione della sua domanda suggerisce che 'status' può avere un valore diverso da' True' o 'False'. È corretto? –
sì lo stato non è in realtà un booleano è una stringa che in seguito si trasformerà in valori booleani se è vero o falso in qualche altra parte del codice – sujay
In che modo "l'altra stringa" '' s 'status' passa da' true' a 'falso'? Perché '' un'altra stringa ''non è la prima nell'array ordinato, si consideri che si lega con' "other stringa" 'sul valore di': status' ed è l'unico dei due ad avere '_NOT_PRESENT' come valore di ': operatore'? –