def valueize(val)
# randomly returns nil or random integer ([-100 to +100] + val)
((rand(100) % 3) == 0) ? nil : (rand(200)-100+val)
end
hash = {
x: 11,
y: 22,
z: 33
}
sort_by_abs = hash.sort_by{ |k, v| (valueize(v)).abs }
sort_by_min = hash.sort_by{ |k, v| (valueize(v)) }
sort_by_max = hash.sort_by{ |k, v| -(valueize(v)) }
What is the most rubyish way of ensuring nil results are always sorted to the bottom, for each of the three sorts?
Conditions:
- Range of potential hash values is unknown (hash values will always be integers)
- valueize method cannot be modified
- sort blocks can be modified
A simple approach (using ick’s
maybejust to keep it compact, do an assignment + conditional if you feel more confortable with it):