G
Garance A Drosehn
Let's say I have a hash with some values in it, and I want to
print out that hash in some sort order. I can:
korder =3D vals.keys.sort { |ka, kb|
vals[kb] <=3D> vals[ka]
}
korder.each { |key| printf " %3d - %s\n", vals[key], key }
That's pretty easy, but what if I want to cascade comparisons
in that sort, such that if the data-values are equal, then I want
the sort order to be based on some other comparison? It
seems to me that I have to:
korder =3D vals.keys.sort { |ka, kb|
sres =3D vals[kb] <=3D> vals[ka]
sres =3D ka <=3D> kb if sres =3D=3D 0
sres
}
korder.each { |key| printf " %3d - %s\n", vals[key], key }
In perl, I can just casade the '<=3D>' comparisons, because it
will treat the zero value as "false". Thus, I could get away
with a one-liner somewhat similar to:
vals[kb] <=3D> vals[ka] or a <=3D> kb
but that doesn't work in ruby. Is there some other way I could
collapse multiple <=3D> comparisons into a single statement?
I do not mind the multi-statement form (now that I've convinced
myself that I can't cascade them the way I could in perl), but I'm
just wondering if there's a better way to do it.
--=20
Garance Alistair Drosehn =3D (e-mail address removed)
Senior Systems Programmer or (e-mail address removed)
Rensselaer Polytechnic Institute; Troy, NY; USA
print out that hash in some sort order. I can:
korder =3D vals.keys.sort { |ka, kb|
vals[kb] <=3D> vals[ka]
}
korder.each { |key| printf " %3d - %s\n", vals[key], key }
That's pretty easy, but what if I want to cascade comparisons
in that sort, such that if the data-values are equal, then I want
the sort order to be based on some other comparison? It
seems to me that I have to:
korder =3D vals.keys.sort { |ka, kb|
sres =3D vals[kb] <=3D> vals[ka]
sres =3D ka <=3D> kb if sres =3D=3D 0
sres
}
korder.each { |key| printf " %3d - %s\n", vals[key], key }
In perl, I can just casade the '<=3D>' comparisons, because it
will treat the zero value as "false". Thus, I could get away
with a one-liner somewhat similar to:
vals[kb] <=3D> vals[ka] or a <=3D> kb
but that doesn't work in ruby. Is there some other way I could
collapse multiple <=3D> comparisons into a single statement?
I do not mind the multi-statement form (now that I've convinced
myself that I can't cascade them the way I could in perl), but I'm
just wondering if there's a better way to do it.
--=20
Garance Alistair Drosehn =3D (e-mail address removed)
Senior Systems Programmer or (e-mail address removed)
Rensselaer Polytechnic Institute; Troy, NY; USA