This repository was archived by the owner on Jun 5, 2024. It is now read-only.
File tree 1 file changed +18
-4
lines changed 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'
2213
2213
$ echo " $s " | ruby -lane ' print $F.sort * " "'
2214
2214
aimed baz foo v22
2215
2215
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
+
2219
2224
$ # descending order
2220
2225
$ # same as: perl -lane 'print join " ", sort {$b cmp $a} @F'
2221
2226
$ echo " $s " | ruby -lane ' print $F.sort { |a,b| b <=> a } * " "'
2222
2227
v22 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
2223
2234
2235
+ ` ` ` bash
2224
2236
$ s= ' floor bat to dubious four'
2225
2237
$ # can also use: ruby -lane 'print $F.sort_by(&:length) * ":"'
2226
2238
$ echo " $s " | ruby -lane ' print $F.sort_by {|a| a.length} * ":"'
2227
2239
to: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} * ":"'
2229
2243
dubious:floor:four:bat:to
2230
2244
` ` `
2231
2245
You can’t perform that action at this time.
0 commit comments