I tried using brackets and using ‘or’ instead of ‘||’ even tried the
sort_by method, any help much appreciated I know this works in perl
(add 13 dollar signs, etc and shake well!):
use strict;
use warnings;
my @char_freq = ([“c”, 2], [“b”, 5], [“a”, 2]);
foreach my $d (sort {$$b[1] <=> $$a[1] || $$a[0] cmp $$b[0] } @char_freq) {
print $$d[0] x $$d[1]
}
Generally you need to do conditional evaluation based on higher prio
results. Using “||” or “or” won’t help here (dunno what Perl does
here).
You want something like
char_freq = [[“c”, 2],[“b”, 5],[“a”, 2]]
sorted_freq = char_freq.sort do |a, b|
c = b[1]<=>a[1]
c == 0 ? a[0]<=>b[0] : c
end
sorted_freq.each do |d|
print d[0]*d[1]
end
You can make your life easier (though less efficient) with a helper:
def multi_compare(*results)
results.each {|c| return c if c != 0}
0
end
Thanks! interesting stuff I’ll read through this closely there are a
rew bits in there that have gone clear over my head at first reading
(the a*b}.join for example).
produces >>
C:\rubysrcs\Yahtzee>ruby -w test3.rb
user system total real
Sort by 1.469000 0.000000 1.469000 ( 1.469000)
Sort 2.703000 0.000000 2.703000 ( 2.703000)
user system total real
Sort by 0.766000 0.000000 0.766000 ( 0.766000)
Sort 2.125000 0.016000 2.141000 ( 2.141000)
Thanks everyone, very interesting. The sort_by method certainly will
just as background info, these techniques are called Schwartzian
transforms, or decorate/sort/undecorate // Guttman-Rosler transform (at
least in other languages’ manuals)
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.