|
39 | 39 | * [Array operations](#array-operations) |
40 | 40 | * [Filtering](#filtering) |
41 | 41 | * [Sorting](#sorting) |
| 42 | + * [Transforming](#transforming) |
42 | 43 |
|
43 | 44 | <br> |
44 | 45 |
|
@@ -2095,7 +2096,67 @@ ECE 92 Om |
2095 | 2096 | CSE 67 Amy |
2096 | 2097 | ``` |
2097 | 2098 |
|
| 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 |
2098 | 2143 |
|
| 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 | +``` |
2099 | 2160 |
|
2100 | 2161 |
|
2101 | 2162 | <br> |
|
0 commit comments