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

Commit b628fa7

Browse files
examples for transforming array
1 parent 63b3663 commit b628fa7

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

ruby_one_liners.md

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
* [Array operations](#array-operations)
4040
* [Filtering](#filtering)
4141
* [Sorting](#sorting)
42+
* [Transforming](#transforming)
4243

4344
<br>
4445

@@ -2095,7 +2096,67 @@ ECE 92 Om
20952096
CSE 67 Amy
20962097
```
20972098
2099+
<br>
2100+
2101+
#### <a name="transforming"></a>Transforming
2102+
2103+
* shuffling elements
2104+
* See also [ruby-doc readlines](https://ruby-doc.org/core-2.5.0/IO.html#method-c-readlines)
2105+
2106+
```bash
2107+
$ s='23 756 -983 5'
2108+
$ echo "$s" | ruby -lane 'print $F.shuffle * " "'
2109+
5 756 -983 23
2110+
$ echo "$s" | ruby -lane 'print $F.shuffle * " "'
2111+
756 5 23 -983
2112+
2113+
$ # randomizing file contents
2114+
$ # note that -n/-p option is not used
2115+
$ ruby -e 'print *readlines.shuffle' poem.txt
2116+
And so are you.
2117+
Violets are blue,
2118+
Roses are red,
2119+
Sugar is sweet,
2120+
2121+
$ # or if shuffle order is known
2122+
$ seq 5 | ruby -e 'print *readlines.values_at(3,1,0,2,4)'
2123+
4
2124+
2
2125+
1
2126+
3
2127+
5
2128+
```
2129+
2130+
* use `map` to transform every element
2131+
2132+
```bash
2133+
$ echo '23 756 -983 5' | ruby -lane 'print $F.map {|n| n.to_i ** 2} * " "'
2134+
529 571536 966289 25
2135+
$ echo 'a b c' | ruby -lane 'print $F.map {|s| "\"#{s}\""} * ","'
2136+
"a","b","c"
2137+
$ echo 'a b c' | ruby -lane 'print $F.map {|s| "\"#{s}\"".upcase} * ","'
2138+
"A","B","C"
2139+
2140+
$ # ASCII int values for each character
2141+
$ echo 'AaBbCc' | ruby -lne 'print $_.split(//).map {|c| c.ord} * " "'
2142+
65 97 66 98 67 99
20982143
2144+
$ # shuffle each field character wise
2145+
$ s='this is a sample sentence'
2146+
$ echo "$s" | ruby -lane 'print $F.map {|s| s.split(//).shuffle * ""} * " "'
2147+
hsti si a mlepas esencnet
2148+
```
2149+
2150+
* reverse array
2151+
2152+
```bash
2153+
$ s='23 756 -983 5'
2154+
$ echo "$s" | ruby -lane 'print $F.reverse * " "'
2155+
5 -983 756 23
2156+
2157+
$ echo 'foobar' | ruby -lne 'print $_.split(//).reverse * ""'
2158+
raboof
2159+
```
20992160
21002161
21012162
<br>

0 commit comments

Comments
 (0)