Skip to content
This repository was archived by the owner on Jun 5, 2024. It is now read-only.

Commit ea341e6

Browse files
improved sort examples
1 parent df809f8 commit ea341e6

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

ruby_one_liners.md

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2213,19 +2213,33 @@ $ # same as: perl -lane 'print join " ", sort @F'
22132213
$ echo "$s" | ruby -lane 'print $F.sort * " "'
22142214
aimed 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 } * " "'
22222227
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
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} * ":"'
22272239
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} * ":"'
22292243
dubious:floor:four:bat:to
22302244
```
22312245

0 commit comments

Comments
 (0)