This repository was archived by the owner on Jun 5, 2024. It is now read-only.
File tree Expand file tree Collapse file tree 1 file changed +18
-4
lines changed Expand file tree Collapse file tree 1 file changed +18
-4
lines changed Original file line number Diff line number Diff line change @@ -2213,19 +2213,33 @@ $ # same as: perl -lane 'print join " ", sort @F'
22132213$ echo " $s " | ruby -lane ' print $F.sort * " "'
22142214aimed baz foo v22
22152215
2216- $ # same as default sort
2217- $ echo " $s " | ruby -lane ' print $F.sort { |a,b| a <=> b } * " "'
2218- aimed baz foo v22
2216+ $ # demonstrating the <=> operator
2217+ $ ruby -e ' puts 4 <=> 2'
2218+ 1
2219+ $ ruby -e ' puts 4 <=> 20'
2220+ -1
2221+ $ ruby -e ' puts 4 <=> 4'
2222+ 0
2223+
22192224$ # descending order
22202225$ # same as: perl -lane 'print join " ", sort {$b cmp $a} @F'
22212226$ echo " $s " | ruby -lane ' print $F.sort { |a,b| b <=> a } * " "'
22222227v22 foo baz aimed
2228+ $ # can also reverse the array after default sorting
2229+ $ echo " $s " | ruby -lane ' print $F.sort.reverse * " "'
2230+ v22 foo baz aimed
2231+ ` ` `
2232+
2233+ * using ` sort_by` to sort based on a key
22232234
2235+ ` ` ` bash
22242236$ s= ' floor bat to dubious four'
22252237$ # can also use: ruby -lane 'print $F.sort_by(&:length) * ":"'
22262238$ echo " $s " | ruby -lane ' print $F.sort_by {|a| a.length} * ":"'
22272239to:bat:four:floor:dubious
2228- $ echo " $s " | ruby -lane ' print $F.sort {|a,b| b.length <=> a.length} * ":"'
2240+
2241+ $ # for descending order, simply negate the key
2242+ $ echo " $s " | ruby -lane ' print $F.sort_by {|a| -a.length} * ":"'
22292243dubious:floor:four:bat:to
22302244` ` `
22312245
You can’t perform that action at this time.
0 commit comments