1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
|
<html><title>Programming Ruby: The Pragmatic Programmer's Guide</title><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><STYLE TYPE="text/css"><!--
BODY { margin-left: 1in;
width: 6in;
font-family: helvetica, arial, sans-serif;
}
H1 { color: #000080;
font-family: helvetica, arial, sans-serif;
font-size: 22pt;
margin-left: 0in
}
H2 { color: #000080; font: bold x-large helvetica, sans-serif;
margin-left: 0in }
H3 { color: #000080; font: bold large helvetica, sans-serif; }
H4 { color: #000080; font: italic large helvetica, sans-serif; }
.ruby { background: #fff0f0 }
.header { color: white }
.subheader { color: #ffdddd }
.sidebar { width: 6in }
span.sans { font-family: helvetica, arial, sans-serif }
-->
</STYLE><table bgcolor="#a03030" cellpadding="3" border="0" cellspacing="0"><tr><td colspan="3"><table bgcolor="#902020" cellpadding="20"><tr><td><h1 class="header">Programming Ruby</h1><h3 class="subheader">The Pragmatic Programmer's Guide</h3></td></tr></table></td></tr><tr><td width="33%" align="left"><a class="subheader" href="tut_containers.html">Previous <</a></td><td width="33%" align="center" valign="middle"><a class="subheader" href="index.html">Contents ^</a><br></td><td width="33%" align="right"><a class="subheader" href="tut_methods.html">Next ></a><br></td></tr></table></head><body bgcolor="white">
<!--
Copyright (c) 2001 by Addison Wesley Longman. This
material may be distributed only subject to the terms and
conditions set forth in the Open Publication License, v1.0 or
later (the latest version is presently available at
http://www.opencontent.org/openpub/).
-->
<h1>Standard Types</h1><hr><br>
<P></P>
So far we've been having fun implementing pieces of our jukebox code,
but we've been negligent. We've looked at arrays, hashes,
and procs, but we haven't really covered the other basic types in
Ruby: numbers, strings, ranges, and regular expressions. Let's
spend a few pages on these basic building blocks now.
<h2>Numbers</h2>
<P></P>
Ruby supports integers and floating point numbers. Integers can be any length (up to a
maximum determined by the amount of free memory on your system).
Integers within a certain range (normally -2<sup>30</sup> to 2<sup>30</sup>-1 or
-2<sup>62</sup> to 2<sup>62</sup>-1) are held internally in binary form,
and are objects of class <code>Fixnum</code>. Integers outside this range are
stored in objects of class <code>Bignum</code> (currently implemented as a
variable-length set of short integers). This process is transparent,
and Ruby automatically manages the conversion back and forth.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
num = 8
7.times do
print num.type, " ", num, "\n"
num *= num
end
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
Fixnum 8
Fixnum 64
Fixnum 4096
Fixnum 16777216
Bignum 281474976710656
Bignum 79228162514264337593543950336
Bignum 6277101735386680763835789423207666416102355444464034512896
</pre></td></tr></table>
<P></P>
You write integers
using an optional leading sign, an
optional base indicator (<code>0</code> for octal, <code>0x</code> for hex, or
<code>0b</code> for binary), followed by a string of digits in the
appropriate base. Underscore characters are ignored in the digit
string.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
123456 # Fixnum
123_456 # Fixnum (underscore ignored)
-543 # Negative Fixnum
123_456_789_123_345_789 # Bignum
0xaabb # Hexadecimal
0377 # Octal
-0b101_010 # Binary (negated)
</pre></td></tr></table>
<P></P>
You can also get the integer value corresponding to an ASCII
character or escape sequence by preceding it with a question mark.
Control and meta combinations can also be generated using
?\C-<em>x</em>, ?\M-<em>x</em>, and ?\M-\C-<em>x</em>.
The control version of a value is the same as
``<code>value & 0x9f</code>''. The meta version of a value is
``<code>value | 0x80</code>''. Finally, the sequence ?\C-? generates an
ASCII delete, <code>0177</code>.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
?a # character code
?\n # code for a newline (0x0a)
?\C-a # control a = ?A & 0x9f = 0x01
?\M-a # meta sets bit 7
?\M-\C-a # meta and control a
?\C-? # delete character
</pre></td></tr></table>
<P></P>
A numeric literal with a decimal point and/or an exponent is turned
into a <code>Float</code> object,
corresponding to the native architecture's
<code>double</code> data type. You must follow the decimal point with a
digit, as <code>1.e3</code> tries to invoke the method <code>e3</code> in class <code>Fixnum</code>.
<P></P>
All numbers are objects, and respond to a variety of messages (listed
in full starting on pages 294, 318,
319, 328, and
354). So, unlike (say) C++, you find the absolute
value of a number by writing <code>aNumber.abs</code>, not
<code>abs(aNumber)</code>.
<P></P>
Integers also support several useful iterators. We've seen one
already---<code>7.times</code> in the code example
on page 49.
Others include <code>upto</code> and
<code>downto</code>, for iterating up and down between two integers, and
<code>step</code>, which is more like a traditional <code>for</code> loop.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
3.times { print "X " }
1.upto(5) { |i| print i, " " }
99.downto(95) { |i| print i, " " }
50.step(80, 5) { |i| print i, " " }
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
X X X 1 2 3 4 5 99 98 97 96 95 50 55 60 65 70 75 80
</pre></td></tr></table>
<P></P>
Finally, a warning for Perl users.
Strings that contain numbers are
not automatically converted into numbers when used in
expressions. This tends to bite most often when reading numbers from a
file. The following code (probably) doesn't do what was intended.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
DATA.each do |line|
vals = line.split # split line, storing tokens in val
print vals[0] + vals[1], " "
end
</pre></td></tr></table>
<P></P>
Feed it a file containing
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
3 4
5 6
7 8
</pre></td></tr></table>
<P></P>
and you'll get the output ``34 56 78.''
What happened?
<P></P>
The problem is that the input was read as strings, not numbers. The plus
operator concatenates strings, so that's what we see in the output.
To fix this, use the <a href="ref_c_string.html#to_i"><code>String#to_i</code></a> method to convert the string to
an integer.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
DATA.each do |line|
vals = line.split
print vals[0].to_i + vals[1].to_i, " "
end
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
7 11 15
</pre></td></tr></table>
<h2>Strings</h2>
<P></P>
Ruby strings are simply sequences of 8-bit
bytes. They normally hold printable
characters, but that is not a requirement; a string can also hold
binary data. Strings are objects of class <code>String</code>.
<P></P>
Strings are often created using string literals---sequences of
characters between delimiters. Because binary data is otherwise
difficult to represent within program source, you can place various
escape sequences in a string literal. Each is replaced with the
corresponding binary value as the program is compiled. The type of
string delimiter determines the degree of substitution performed.
Within single-quoted strings, two consecutive backslashes are replaced
by a single backslash, and a backslash followed by a single quote
becomes a single quote.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>'escape using "\\"'</code></td>
<td valign="top"></td>
<td valign="top"><code>escape using "\"</code></td>
</tr>
<tr>
<td valign="top"><code>'That\'s right'</code></td>
<td valign="top"></td>
<td valign="top"><code>That's right</code></td>
</tr>
</table>
<P></P>
<P></P>
Double-quoted strings support a boatload more escape sequences. The
most common is probably ``\n'', the newline character.
Table 18.2 on page 205 gives the complete list. In addition,
you can substitute the value of any Ruby expression into a string
using the sequence <code>#{</code> <em>expr</em> <code>}</code>.
If the expression is just a global variable, a class variable, or an instance variable,
you can omit the braces.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>"Seconds/day: #{24*60*60}"</code></td>
<td valign="top"></td>
<td valign="top"><code>Seconds/day: 86400</code></td>
</tr>
<tr>
<td valign="top"><code>"#{'Ho! '*3}Merry Christmas"</code></td>
<td valign="top"></td>
<td valign="top"><code>Ho! Ho! Ho! Merry Christmas</code></td>
</tr>
<tr>
<td valign="top"><code>"This is line #$."</code></td>
<td valign="top"></td>
<td valign="top"><code>This is line 3</code></td>
</tr>
</table>
<P></P>
<P></P>
There are three more ways to construct string literals:
<code>%q</code>, <code>%Q</code>, and ``here documents.''
<P></P>
<code>%q</code> and <code>%Q</code> start delimited single- and double-quoted
strings.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>%q/general single-quoted string/</code></td>
<td valign="top"></td>
<td valign="top"><code>general single-quoted string</code></td>
</tr>
<tr>
<td valign="top"><code>%Q!general double-quoted string!</code></td>
<td valign="top"></td>
<td valign="top"><code>general double-quoted string</code></td>
</tr>
<tr>
<td valign="top"><code>%Q{Seconds/day: #{24*60*60}}</code></td>
<td valign="top"></td>
<td valign="top"><code>Seconds/day: 86400</code></td>
</tr>
</table>
<P></P>
<P></P>
The character following the ``q'' or ``Q'' is the delimiter. If it is
an opening bracket, brace, parenthesis, or less-than sign, the string
is read until the matching close symbol is found. Otherwise the string
is read until the next occurrence of the same delimiter.
<P></P>
Finally, you can construct a string using a <em>here document</em>.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
aString = <<END_OF_STRING
The body of the string
is the input lines up to
one ending with the same
text that followed the '<<'
END_OF_STRING
</pre></td></tr></table>
<P></P>
A here document consists of lines in the source up to, but not
including, the terminating string that you specify after the <code><<</code>
characters. Normally, this terminator must start in the first
column. However, if you put a minus sign after the <code><<</code>
characters, you can indent the terminator.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
print <<-STRING1, <<-STRING2
Concat
STRING1
enate
STRING2
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
Concat
enate
<P></P>
</pre></td></tr></table>
<h3>Working with Strings</h3>
<P></P>
<code>String</code> is probably the largest built-in Ruby class, with over 75
standard methods. We won't go through them all here; the library
reference has a complete list. Instead, we'll look at
some common string idioms---things that are likely to pop up during
day-to-day programming.
<P></P>
Let's get back to our jukebox. Although it's designed to be connected
to the Internet, it also holds copies of some popular songs on a local
hard drive. That way, if a squirrel chews through our 'net connection
we'll still be able to entertain the customers.
<P></P>
For historical reasons (are there any other kind?), the list of songs
is stored as rows in a flat file. Each row holds the name of the file
containing the song, the song's duration, the artist, and the title,
all in vertical-bar-separated fields. A typical file might
start:
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
/jazz/j00132.mp3 | 3:45 | Fats Waller | Ain't Misbehavin'
/jazz/j00319.mp3 | 2:58 | Louis Armstrong | Wonderful World
/bgrass/bg0732.mp3| 4:09 | Strength in Numbers | Texas Red
: : : :
</pre></td></tr></table>
<P></P>
Looking at the data, it's clear that we'll be using some of class
<code>String</code>'s many methods to extract and clean up the fields before we
create <code>Song</code> objects based on them. At a minimum, we'll need to:
<P></P>
<ul>
<li> break the line into fields,
</li><li> convert the running time from mm:ss to seconds, and
</li><li> remove those extra spaces from the artist's name.
</li></ul>
<P></P>
Our first task is to split each line into fields, and
<a href="ref_c_string.html#split"><code>String#split</code></a> will do the job nicely. In
this case, we'll pass <code>split</code> a regular expression,
<code>/\s*\|\s*/</code>, which splits the line into tokens
wherever <code>split</code> finds a vertical bar, optionally surrounded by
spaces. And, because the line read from the file has a trailing
newline, we'll use <a href="ref_c_string.html#chomp"><code>String#chomp</code></a> to strip it off just before we
apply the split.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
songs = SongList.new
<P></P>
songFile.each do |line|
file, length, name, title = line.chomp.split(/\s*\|\s*/)
songs.append Song.new(title, name, length)
end
puts songs[1]
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
Song: Wonderful World--Louis Armstrong (2:58)
</pre></td></tr></table>
<P></P>
Unfortunately, whoever created the original file entered the artists'
names in columns, so some of them contain extra spaces. These will
look ugly on our high-tech, super-twist, flat-panel Day-Glo display, so
we'd better remove these extra spaces before we go much further.
There are many ways of doing this, but
probably the simplest is <a href="ref_c_string.html#squeeze"><code>String#squeeze</code></a>, which trims runs of
repeated characters. We'll use the <code>squeeze!</code> form of the
method, which alters the string in place.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
songs = SongList.new
<P></P>
songFile.each do |line|
file, length, name, title = line.chomp.split(/\s*\|\s*/)
name.squeeze!(" ")
songs.append Song.new(title, name, length)
end
puts songs[1]
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
Song: Wonderful World--Louis Armstrong (2:58)
</pre></td></tr></table>
<P></P>
Finally, there's the minor matter of the time format: the file says
2:58, and we want the number of seconds, 178. We could use
<code>split</code> again, this time splitting the time field around the
colon character.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
mins, secs = length.split(/:/)
</pre></td></tr></table>
<P></P>
Instead, we'll use a related method. <a href="ref_c_string.html#scan"><code>String#scan</code></a> is similar to
<code>split</code> in that it breaks a string into chunks based on a
pattern. However, unlike <code>split</code>, with <code>scan</code> you
specify the pattern that you want the chunks to match. In this case,
we want to match one or more digits for both the minutes and seconds
component. The pattern for one or more digits is <code>/\d+/</code>.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
songs = SongList.new
songFile.each do |line|
file, length, name, title = line.chomp.split(/\s*\|\s*/)
name.squeeze!(" ")
mins, secs = length.scan(/\d+/)
songs.append Song.new(title, name, mins.to_i*60+secs.to_i)
end
puts songs[1]
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
Song: Wonderful World--Louis Armstrong (178)
</pre></td></tr></table>
<P></P>
Our jukebox has a keyword search capability. Given a word from a song
title or an artist's name, it will list all matching tracks. Type in
``fats,'' and it might come back with songs by Fats Domino, Fats
Navarro, and Fats Waller, for example. We'll implement this by
creating an indexing class. Feed it an object and some strings,
and it will index that object under every word (of two or more
characters) that occurs in those strings. This will illustrate a few
more of class <code>String</code>'s many methods.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class WordIndex
def initialize
@index = Hash.new(nil)
end
def index(anObject, *phrases)
phrases.each do |aPhrase|
aPhrase.scan /\w[-\w']+/ do |aWord| # extract each word
aWord.downcase!
@index[aWord] = [] if @index[aWord].nil?
@index[aWord].push(anObject)
end
end
end
def lookup(aWord)
@index[aWord.downcase]
end
end
</pre></td></tr></table>
<P></P>
The <a href="ref_c_string.html#scan"><code>String#scan</code></a> method extracts elements from a string that
match a regular expression. In this case, the pattern
``<code>\w[-\w']+</code>'' matches any character that can
appear in a word, followed by one or more of the things specified in
the brackets (a hyphen, another word character, or a single quote). We'll talk
more about regular expressions beginning on page 58. To make our
searches case insensitive, we map both the words we extract and the
words used as keys during the lookup to lowercase. Note the
exclamation mark at the end of the first <code>downcase!</code> method
name. As with the <code>squeeze!</code> method we used previously, this is
an indication that the method will modify the receiver in place, in this
case converting the string to lowercase.<em>[There's a minor bug
in this code example: the song ``Gone, Gone, Gone'' would get
indexed three times. Can you come up with a fix?]</em>
<P></P>
We'll extend our <code>SongList</code> class to index songs as they're added,
and add a method to look up a song given a word.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class SongList
def initialize
@songs = Array.new
@index = WordIndex.new
end
def append(aSong)
@songs.push(aSong)
@index.index(aSong, aSong.name, aSong.artist)
self
end
def lookup(aWord)
@index.lookup(aWord)
end
end
</pre></td></tr></table>
<P></P>
Finally, we'll test it all.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
songs = SongList.new
songFile.each do |line|
file, length, name, title = line.chomp.split(/\s*\|\s*/)
name.squeeze!(" ")
mins, secs = length.scan(/\d+/)
songs.append Song.new(title, name, mins.to_i*60+secs.to_i)
end
puts songs.lookup("Fats")
puts songs.lookup("ain't")
puts songs.lookup("RED")
puts songs.lookup("WoRlD")
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
Song: Ain't Misbehavin'--Fats Waller (225)
Song: Ain't Misbehavin'--Fats Waller (225)
Song: Texas Red--Strength in Numbers (249)
Song: Wonderful World--Louis Armstrong (178)
</pre></td></tr></table>
<P></P>
We could spend the next 50 pages looking at all the methods in class
<code>String</code>. However, let's move on instead to look at a simpler
datatype: ranges.
<h2>Ranges</h2>
<P></P>
Ranges occur everywhere: January to December, 0 to 9, rare to
well-done, lines 50 through 67, and so on. If Ruby is to help us
model reality, it seems natural for it to support these ranges. In
fact, Ruby goes one better: it actually uses ranges to implement three
separate features: sequences, conditions, and intervals.<h3>Ranges as Sequences</h3>
<P></P>
The first and perhaps most natural use of ranges is to express a
sequence.
Sequences have a start point, an end point, and a way to
produce successive values in the sequence. In Ruby, these sequences
are created using the ``..'' and ``...'' range operators. The
two-dot form creates an inclusive range, while the three-dot form
creates a range that excludes the specified high value.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
1..10
'a'..'z'
0...anArray.length
</pre></td></tr></table>
<P></P>
In Ruby, unlike in some earlier versions of Perl, ranges are not
represented internally as lists: the sequence 1..100000 is held as a
<code>Range</code> object containing references to two <code>Fixnum</code> objects. If
you need to, you can convert a range to a list using the
<code>to_a</code> method.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>(1..10).to_a</code></td>
<td valign="top"></td>
<td valign="top"><code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</code></td>
</tr>
<tr>
<td valign="top"><code>('bar'..'bat').to_a</code></td>
<td valign="top"></td>
<td valign="top"><code>["bar", "bas", "bat"]</code></td>
</tr>
</table>
<P></P>
<P></P>
Ranges implement methods that let you iterate over them and test their
contents in a variety of ways.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>digits = 0..9</code></td>
</tr>
<tr>
<td valign="top"><code>digits.include?(5)</code></td>
<td valign="top"></td>
<td valign="top"><code>true</code></td>
</tr>
<tr>
<td valign="top"><code>digits.min</code></td>
<td valign="top"></td>
<td valign="top"><code>0</code></td>
</tr>
<tr>
<td valign="top"><code>digits.max</code></td>
<td valign="top"></td>
<td valign="top"><code>9</code></td>
</tr>
<tr>
<td valign="top"><code>digits.reject {|i| i < 5 }</code></td>
<td valign="top"></td>
<td valign="top"><code>[5, 6, 7, 8, 9]</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>digits.each do |digit|</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> dial(digit)</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>end</code></td>
</tr>
</table>
<P></P>
<P></P>
So far we've shown ranges of numbers and strings. However, as you'd
expect from an object-oriented language, Ruby can create ranges based
on objects that you define. The only constraints are that the objects
must respond to <code>succ</code> by returning the next object in sequence
and the objects must be comparable using <code><=></code>,
the general comparison operator.
Sometimes called the
spaceship operator, <code><=></code> compares two values, returning -1, 0, or +1
depending on whether the first is less than, equal to, or greater than
the second.
<P></P>
Here's a simple class that represents rows of ``#'' signs. We might
use it as a text-based stub when testing the jukebox volume control.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class VU
<P></P>
include Comparable
<P></P>
attr :volume
<P></P>
def initialize(volume) # 0..9
@volume = volume
end
<P></P>
def inspect
'#' * @volume
end
<P></P>
# Support for ranges
<P></P>
def <=>(other)
self.volume <=> other.volume
end
<P></P>
def succ
raise(IndexError, "Volume too big") if @volume >= 9
VU.new(@volume.succ)
end
end
</pre></td></tr></table>
<P></P>
We can test it by creating a range of <code>VU</code> objects.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>medium = VU.new(4)..VU.new(7)</code></td>
</tr>
<tr>
<td valign="top"><code>medium.to_a</code></td>
<td valign="top"></td>
<td valign="top"><code>[####, #####, ######, #######]</code></td>
</tr>
<tr>
<td valign="top"><code>medium.include?(VU.new(3))</code></td>
<td valign="top"></td>
<td valign="top"><code>false</code></td>
</tr>
</table>
<P></P>
<h3>Ranges as Conditions</h3>
<P></P>
As well as representing sequences, ranges may also be used as
conditional expressions.
For example, the
following code fragment prints sets of lines from standard input,
where the first line in each set contains the word ``start'' and the
last line the word ``end.''
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
while gets
print if /start/../end/
end
</pre></td></tr></table>
<P></P>
Behind the scenes, the range keeps track of the state of each of the
tests. We'll show some examples of this in the description of loops
that starts on page 84.
<h3>Ranges as Intervals</h3>
<P></P>
A final use of the versatile range is as an interval test:
seeing if
some value falls within the interval represented by the range.
This is done using <code>===</code>, the case equality operator.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>(1..10) === 5</code></td>
<td valign="top"></td>
<td valign="top"><code>true</code></td>
</tr>
<tr>
<td valign="top"><code>(1..10) === 15</code></td>
<td valign="top"></td>
<td valign="top"><code>false</code></td>
</tr>
<tr>
<td valign="top"><code>(1..10) === 3.14159</code></td>
<td valign="top"></td>
<td valign="top"><code>true</code></td>
</tr>
<tr>
<td valign="top"><code>('a'..'j') === 'c'</code></td>
<td valign="top"></td>
<td valign="top"><code>true</code></td>
</tr>
<tr>
<td valign="top"><code>('a'..'j') === 'z'</code></td>
<td valign="top"></td>
<td valign="top"><code>false</code></td>
</tr>
</table>
<P></P>
<P></P>
The example of a case expression on page 83 shows this
test in action, determining a jazz style given a year.
<h2>Regular Expressions</h2>
<P></P>
Back on page 53 when we were creating a song list
from a file, we used a regular expression to match the field delimiter
in the input file. We claimed that the expression <code>line.split(/\s*\|\s*/)</code> matched a vertical bar surrounded by optional
whitespace. Let's explore regular expressions in more detail to see why
this claim is true.
<P></P>
Regular expressions are used to match patterns against strings.
Ruby provides built-in support that makes pattern matching and
substitution convenient and concise. In this section we'll work
through all the main features of regular expressions. There are some
details we won't cover: have a look at page 207 for
more information.
<P></P>
Regular expressions are objects of type <code>Regexp</code>. They can be
created by calling the constructor explicitly or by using the literal
forms /<em>pattern</em>/ and %r\<em>pattern</em>\.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>a = Regexp.new('^\s*[a-z]')</code></td>
<td valign="top"></td>
<td valign="top"><code>/^\s*[a-z]/</code></td>
</tr>
<tr>
<td valign="top"><code>b = /^\s*[a-z]/</code></td>
<td valign="top"></td>
<td valign="top"><code>/^\s*[a-z]/</code></td>
</tr>
<tr>
<td valign="top"><code>c = %r{^\s*[a-z]}</code></td>
<td valign="top"></td>
<td valign="top"><code>/^\s*[a-z]/</code></td>
</tr>
</table>
<P></P>
<P></P>
Once you have a regular expression object, you can match it against a
string using <code>Regexp#match(<i>aString</i>)</code>
or the match
operators <code>=~</code>
(positive match) and <code>!~</code>
(negative match). The
match operators are defined for both <code>String</code> and <code>Regexp</code> objects.
If both operands of the match operator are <code>Strings</code>, the one on
the right will be converted to a regular expression.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>a = "Fats Waller"</code></td>
</tr>
<tr>
<td valign="top"><code>a =~ /a/</code></td>
<td valign="top"></td>
<td valign="top"><code>1</code></td>
</tr>
<tr>
<td valign="top"><code>a =~ /z/</code></td>
<td valign="top"></td>
<td valign="top"><code>nil</code></td>
</tr>
<tr>
<td valign="top"><code>a =~ "ll"</code></td>
<td valign="top"></td>
<td valign="top"><code>7</code></td>
</tr>
</table>
<P></P>
<P></P>
The match operators return the character position at which the match
occurred. They also have the side effect of setting a whole load of
Ruby variables. <code>$&</code> receives the part of the string that was
matched by the pattern, <code>$`</code> receives the part of the string
that preceded the match, and <code>$'</code> receives the string after the
match. We can use this to write a method, <code>showRE</code>, which
illustrates where a particular pattern matches.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>def showRE(a,re)</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> if a =~ re</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> "#{$`}<<#{$&}>>#{$'}"</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> else</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> "no match"</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td valign="top"><code>showRE('very interesting', /t/)</code></td>
<td valign="top"></td>
<td valign="top"><code>very in<<t>>eresting</code></td>
</tr>
<tr>
<td valign="top"><code>showRE('Fats Waller', /ll/)</code></td>
<td valign="top"></td>
<td valign="top"><code>Fats Wa<<ll>>er</code></td>
</tr>
</table>
<P></P>
<P></P>
The match also sets the thread-global variables <code>$~</code> and
<code>$1</code> through <code>$9</code>.
The variable <code>$~</code> is a <code>MatchData</code> object
(described beginning on page 340) that holds everything you might
want to know about the match. <code>$1</code> and so on hold the values of
parts of the match. We'll talk about these later. And for people who
cringe when they see these Perl-like variable names, stay
tuned. There's good news at the end of the chapter.
<h3>Patterns</h3>
<P></P>
Every regular expression contains a pattern, which is used to match
the regular expression against a string.
<P></P>
Within a pattern, all characters except ., |, (, ), [, {, +, \,
^, $, *, and ? match themselves.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>showRE('kangaroo', /angar/)</code></td>
<td valign="top"></td>
<td valign="top"><code>k<<angar>>oo</code></td>
</tr>
<tr>
<td valign="top"><code>showRE('!@%&-_=+', /%&/)</code></td>
<td valign="top"></td>
<td valign="top"><code>!@<<%&>>-_=+</code></td>
</tr>
</table>
<P></P>
<P></P>
If you want to match one of these special characters literally,
precede it with a backslash.
This explains part of the pattern we used
to split the song line, <code>/\s*\|\s*/</code>. The <code>\|</code> means
``match a vertical bar.'' Without the backslash, the ``<code>|</code>'' would have
meant <em>alternation</em> (which we'll describe later).
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>showRE('yes | no', /\|/)</code></td>
<td valign="top"></td>
<td valign="top"><code>yes <<|>> no</code></td>
</tr>
<tr>
<td valign="top"><code>showRE('yes (no)', /\(no\)/)</code></td>
<td valign="top"></td>
<td valign="top"><code>yes <<(no)>></code></td>
</tr>
<tr>
<td valign="top"><code>showRE('are you sure?', /e\?/)</code></td>
<td valign="top"></td>
<td valign="top"><code>are you sur<<e?>></code></td>
</tr>
</table>
<P></P>
<P></P>
A backslash followed by an alphanumeric character is used to introduce
a special match construct, which we'll cover later. In addition, a
regular expression may contain <code>#{...}</code> expression
substitutions.
<h3>Anchors</h3>
<P></P>
By default, a regular expression will try to find the first match for
the pattern in a string. Match <code>/iss/</code> against the string
``Mississippi,'' and it will find the substring ``iss'' starting at
position one. But what if you want to force a pattern to match only at
the start or end of a string?
<P></P>
The patterns <code>^</code>
and <code>$</code> match the beginning and end of a
line, respectively. These are often used to <em>anchor</em> a pattern
match: for example, <code>/^option/</code> matches the word ``option'' only
if it appears at the start of a line. The sequence <code>\A</code> matches
the beginning of a string, and <code>\z</code> and <code>\Z</code> match the
end of a string. (Actually, <code>\Z</code> matches the end of a string
<em>unless</em> the string ends with a ``\n'', it which case it
matches just before the ``\n''.)
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>showRE("this is\nthe time", /^the/)</code></td>
<td valign="top"></td>
<td valign="top"><code>this is\n<<the>> time</code></td>
</tr>
<tr>
<td valign="top"><code>showRE("this is\nthe time", /is$/)</code></td>
<td valign="top"></td>
<td valign="top"><code>this <<is>>\nthe time</code></td>
</tr>
<tr>
<td valign="top"><code>showRE("this is\nthe time", /\Athis/)</code></td>
<td valign="top"></td>
<td valign="top"><code><<this>> is\nthe time</code></td>
</tr>
<tr>
<td valign="top"><code>showRE("this is\nthe time", /\Athe/)</code></td>
<td valign="top"></td>
<td valign="top"><code>no match</code></td>
</tr>
</table>
<P></P>
<P></P>
Similarly, the patterns <code>\b</code> and <code>\B</code> match word boundaries
and nonword boundaries, respectively. Word characters are letters,
numbers, and underscore.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>showRE("this is\nthe time", /\bis/)</code></td>
<td valign="top"></td>
<td valign="top"><code>this <<is>>\nthe time</code></td>
</tr>
<tr>
<td valign="top"><code>showRE("this is\nthe time", /\Bis/)</code></td>
<td valign="top"></td>
<td valign="top"><code>th<<is>> is\nthe time</code></td>
</tr>
</table>
<P></P>
<h3>Character Classes</h3>
<P></P>
A character class is a set of characters between brackets:
<code>[</code><em>characters</em><code>]</code> matches any single character between the
brackets. <code>[aeiou]</code> will match a vowel, <code>[,.:;!?]</code> matches
punctuation, and so on. The significance of the special regular
expression characters---<code>.|()[{+^$*?</code>---is turned off inside
the brackets. However, normal string substitution still occurs, so
(for example) <code>\b</code> represents a backspace character and
<code>\n</code> a newline (see Table 18.2 on page 205). In addition,
you can use the abbreviations shown in Table 5.1 on page 62, so
that (for example) <code>\s</code> matches any whitespace character, not
just a literal space.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>showRE('It costs $12.', /[aeiou]/)</code></td>
<td valign="top"></td>
<td valign="top"><code>It c<<o>>sts $12.</code></td>
</tr>
<tr>
<td valign="top"><code>showRE('It costs $12.', /[\s]/)</code></td>
<td valign="top"></td>
<td valign="top"><code>It<< >>costs $12.</code></td>
</tr>
</table>
<P></P>
<P></P>
Within the brackets, the sequence c<sub>1</sub>-c<sub>2</sub> represents all the
characters between c<sub>1</sub> and c<sub>2</sub>, inclusive.
<P></P>
If you want to include the literal characters <code>]</code> and <code>-</code> within
a character class, they must appear at the start.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>a = 'Gamma [Design Patterns-page 123]'</code></td>
</tr>
<tr>
<td valign="top"><code>showRE(a, /[]]/)</code></td>
<td valign="top"></td>
<td valign="top"><code>Gamma [Design Patterns-page 123<<]>></code></td>
</tr>
<tr>
<td valign="top"><code>showRE(a, /[B-F]/)</code></td>
<td valign="top"></td>
<td valign="top"><code>Gamma [<<D>>esign Patterns-page 123]</code></td>
</tr>
<tr>
<td valign="top"><code>showRE(a, /[-]/)</code></td>
<td valign="top"></td>
<td valign="top"><code>Gamma [Design Patterns<<->>page 123]</code></td>
</tr>
<tr>
<td valign="top"><code>showRE(a, /[0-9]/)</code></td>
<td valign="top"></td>
<td valign="top"><code>Gamma [Design Patterns-page <<1>>23]</code></td>
</tr>
</table>
<P></P>
<P></P>
Put a <code>^</code>
immediately after the opening bracket to negate a
character class: <code>[^a-z]</code> matches any character that isn't a
lowercase alphabetic.
<P></P>
Some character classes are used so frequently that Ruby provides
abbreviations for them. These abbreviations are listed in Table
5.1 on page 62---they may be used both within brackets and in
the body of a pattern.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>showRE('It costs $12.', /\s/)</code></td>
<td valign="top"></td>
<td valign="top"><code>It<< >>costs $12.</code></td>
</tr>
<tr>
<td valign="top"><code>showRE('It costs $12.', /\d/)</code></td>
<td valign="top"></td>
<td valign="top"><code>It costs $<<1>>2.</code></td>
</tr>
</table>
<P></P>
<P></P>
<table border="2" width="500" bgcolor="#ffe0e0"><tr><td>
<b>Character class abbreviations</b>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3">
<tr bgcolor="#ff9999">
<td valign="top"><b>Sequence</b></td>
<td valign="top"><b>As [ ... ]</b></td>
<td valign="top"><b>Meaning</b></td>
</tr>
<tr>
<td valign="top"><code>\d</code></td>
<td valign="top">[0-9]</td>
<td valign="top">Digit character</td>
</tr>
<tr>
<td valign="top"><code>\D</code></td>
<td valign="top">[^0-9]</td>
<td valign="top">Nondigit</td>
</tr>
<tr>
<td valign="top"><code>\s</code></td>
<td valign="top">[\s\t\r\n\f]</td>
<td valign="top">Whitespace character</td>
</tr>
<tr>
<td valign="top"><code>\S</code></td>
<td valign="top">[^\s\t\r\n\f]</td>
<td valign="top">Nonwhitespace character</td>
</tr>
<tr>
<td valign="top"><code>\w</code></td>
<td valign="top">[A-Za-z0-9_]</td>
<td valign="top">Word character</td>
</tr>
<tr>
<td valign="top"><code>\W</code></td>
<td valign="top">[^A-Za-z0-9_]</td>
<td valign="top">Nonword character</td>
</tr>
<tr><td colspan="9" bgcolor="#ff9999" height="2"><img src="dot.gif" width="1" height="1"></td></tr></table>
<P></P>
</td></tr></table>
<P></P>
Finally, a period (``.'') appearing outside brackets represents any
character except a newline (and in multiline mode it matches a newline,
too).
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>a = 'It costs $12.'</code></td>
</tr>
<tr>
<td valign="top"><code>showRE(a, /c.s/)</code></td>
<td valign="top"></td>
<td valign="top"><code>It <<cos>>ts $12.</code></td>
</tr>
<tr>
<td valign="top"><code>showRE(a, /./)</code></td>
<td valign="top"></td>
<td valign="top"><code><<I>>t costs $12.</code></td>
</tr>
<tr>
<td valign="top"><code>showRE(a, /\./)</code></td>
<td valign="top"></td>
<td valign="top"><code>It costs $12<<.>></code></td>
</tr>
</table>
<P></P>
<h3>Repetition</h3>
<P></P>
When we specified the pattern that split the song list line, <code>/\s*\|\s*/</code>, we said we wanted to match a vertical bar surrounded by
an arbitrary amount of whitespace. We now know that the <code>\s</code>
sequences match a single whitespace character, so it seems likely that
the asterisks somehow mean ``an arbitrary amount.'' In fact, the
asterisk is one of a number of modifiers that allow you to match multiple
occurrences of a pattern.
<P></P>
If <em>r</em> stands for the immediately preceding regular expression
within a pattern, then:
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3">
<tr>
<td valign="top"><em>r</em><code>*</code></td>
<td valign="top">matches zero or more occurrences of <em>r</em>.</td>
</tr>
<tr>
<td valign="top"><em>r</em><code>+</code></td>
<td valign="top">matches one or more occurrences of <em>r</em>.</td>
</tr>
<tr>
<td valign="top"><em>r</em><code>?</code></td>
<td valign="top">matches zero or one occurrence of <em>r</em>.</td>
</tr>
<tr>
<td valign="top"><em>r</em><code>{m,n}</code></td>
<td valign="top">matches at least ``m'' and at most ``n'' occurrences of <em>r</em>.</td>
</tr>
<tr>
<td valign="top"><em>r</em><code>{m,}</code></td>
<td valign="top">matches at least ``m'' occurrences of <em>r</em>.</td>
</tr>
</table>
<P></P>
These repetition constructs have a high precedence---they bind only to
the immediately preceding regular expression in the
pattern. <code>/ab+/</code> matches an ``a'' followed by one or more ``b''s,
not a sequence of ``ab''s. You have to be careful with the <code>*</code>
construct too---the pattern /a*/ will match any string; every string
has zero or more ``a''s.
<P></P>
These patterns are called <em>greedy</em>,
because by default they will
match as much of the string as they can. You can alter this
behavior, and have them match the minimum, by adding a question mark
suffix.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>a = "The moon is made of cheese"</code></td>
</tr>
<tr>
<td valign="top"><code>showRE(a, /\w+/)</code></td>
<td valign="top"></td>
<td valign="top"><code><<The>> moon is made of cheese</code></td>
</tr>
<tr>
<td valign="top"><code>showRE(a, /\s.*\s/)</code></td>
<td valign="top"></td>
<td valign="top"><code>The<< moon is made of >>cheese</code></td>
</tr>
<tr>
<td valign="top"><code>showRE(a, /\s.*?\s/)</code></td>
<td valign="top"></td>
<td valign="top"><code>The<< moon >>is made of cheese</code></td>
</tr>
<tr>
<td valign="top"><code>showRE(a, /[aeiou]{2,99}/)</code></td>
<td valign="top"></td>
<td valign="top"><code>The m<<oo>>n is made of cheese</code></td>
</tr>
<tr>
<td valign="top"><code>showRE(a, /mo?o/)</code></td>
<td valign="top"></td>
<td valign="top"><code>The <<moo>>n is made of cheese</code></td>
</tr>
</table>
<P></P>
<h3>Alternation</h3>
<P></P>
We know that the vertical bar is special, because our line splitting
pattern had to escape it with a backslash. That's because an unescaped
vertical bar ``|'' matches either the regular expression that
precedes it or the regular expression that follows it.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>a = "red ball blue sky"</code></td>
</tr>
<tr>
<td valign="top"><code>showRE(a, /d|e/)</code></td>
<td valign="top"></td>
<td valign="top"><code>r<<e>>d ball blue sky</code></td>
</tr>
<tr>
<td valign="top"><code>showRE(a, /al|lu/)</code></td>
<td valign="top"></td>
<td valign="top"><code>red b<<al>>l blue sky</code></td>
</tr>
<tr>
<td valign="top"><code>showRE(a, /red ball|angry sky/)</code></td>
<td valign="top"></td>
<td valign="top"><code><<red ball>> blue sky</code></td>
</tr>
</table>
<P></P>
<P></P>
There's a trap for the unwary here, as ``|'' has a very low precedence.
The last example above matches ``red ball'' or ``angry sky'', not ``red
ball sky'' or ``red angry sky''. To match ``red ball sky'' or ``red
angry sky'', you'd need to override
the default precedence using grouping.
<h3>Grouping</h3>
<P></P>
You can use parentheses to group terms within a regular
expression. Everything within the group is treated as a single regular
expression.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>showRE('banana', /an*/)</code></td>
<td valign="top"></td>
<td valign="top"><code>b<<an>>ana</code></td>
</tr>
<tr>
<td valign="top"><code>showRE('banana', /(an)*/)</code></td>
<td valign="top"></td>
<td valign="top"><code><<>>banana</code></td>
</tr>
<tr>
<td valign="top"><code>showRE('banana', /(an)+/)</code></td>
<td valign="top"></td>
<td valign="top"><code>b<<anan>>a</code></td>
</tr>
</table>
<P></P>
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>a = 'red ball blue sky'</code></td>
</tr>
<tr>
<td valign="top"><code>showRE(a, /blue|red/)</code></td>
<td valign="top"></td>
<td valign="top"><code><<red>> ball blue sky</code></td>
</tr>
<tr>
<td valign="top"><code>showRE(a, /(blue|red) \w+/)</code></td>
<td valign="top"></td>
<td valign="top"><code><<red ball>> blue sky</code></td>
</tr>
<tr>
<td valign="top"><code>showRE(a, /(red|blue) \w+/)</code></td>
<td valign="top"></td>
<td valign="top"><code><<red ball>> blue sky</code></td>
</tr>
<tr>
<td valign="top"><code>showRE(a, /red|blue \w+/)</code></td>
<td valign="top"></td>
<td valign="top"><code><<red>> ball blue sky</code></td>
</tr>
</table>
<P></P>
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>showRE(a, /red (ball|angry) sky/)</code></td>
<td valign="top"></td>
<td valign="top"><code>no match</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>a = 'the red angry sky'</code></td>
</tr>
<tr>
<td valign="top"><code>showRE(a, /red (ball|angry) sky/)</code></td>
<td valign="top"></td>
<td valign="top"><code>the <<red angry sky>></code></td>
</tr>
</table>
<P></P>
<P></P>
Parentheses are also used to collect the results of pattern
matching. Ruby counts opening parentheses, and for each stores the result of
the partial match between it and the corresponding closing
parenthesis. You can use this partial match both within the remainder
of the pattern and in your Ruby program. Within the pattern, the
sequence <code>\1</code> refers to the match of the first group, <code>\2</code> the
second group, and so on. Outside the pattern, the special variables
<code>$1</code>, <code>$2</code>, and so on, serve the same purpose.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>"12:50am" =~ /(\d\d):(\d\d)(..)/</code></td>
<td valign="top"></td>
<td valign="top"><code>0</code></td>
</tr>
<tr>
<td valign="top"><code>"Hour is #$1, minute #$2"</code></td>
<td valign="top"></td>
<td valign="top"><code>"Hour is 12, minute 50"</code></td>
</tr>
<tr>
<td valign="top"><code>"12:50am" =~ /((\d\d):(\d\d))(..)/</code></td>
<td valign="top"></td>
<td valign="top"><code>0</code></td>
</tr>
<tr>
<td valign="top"><code>"Time is #$1"</code></td>
<td valign="top"></td>
<td valign="top"><code>"Time is 12:50"</code></td>
</tr>
<tr>
<td valign="top"><code>"Hour is #$2, minute #$3"</code></td>
<td valign="top"></td>
<td valign="top"><code>"Hour is 12, minute 50"</code></td>
</tr>
<tr>
<td valign="top"><code>"AM/PM is #$4"</code></td>
<td valign="top"></td>
<td valign="top"><code>"AM/PM is am"</code></td>
</tr>
</table>
<P></P>
<P></P>
The ability to use part of the current match later in that match
allows you to look for various forms of repetition.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code># match duplicated letter</code></td>
</tr>
<tr>
<td valign="top"><code>showRE('He said "Hello"', /(\w)\1/)</code></td>
<td valign="top"></td>
<td valign="top"><code>He said "He<<ll>>o"</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code># match duplicated substrings</code></td>
</tr>
<tr>
<td valign="top"><code>showRE('Mississippi', /(\w+)\1/)</code></td>
<td valign="top"></td>
<td valign="top"><code>M<<ississ>>ippi</code></td>
</tr>
</table>
<P></P>
<P></P>
You can also use back references to match delimiters.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>showRE('He said "Hello"', /(["']).*?\1/)</code></td>
<td valign="top"></td>
<td valign="top"><code>He said <<"Hello">></code></td>
</tr>
<tr>
<td valign="top"><code>showRE("He said 'Hello'", /(["']).*?\1/)</code></td>
<td valign="top"></td>
<td valign="top"><code>He said <<'Hello'>></code></td>
</tr>
</table>
<P></P>
<h3>Pattern-Based Substitution</h3>
<P></P>
Sometimes finding a pattern in a string is good enough.
If a friend
challenges you to find a word that contains the letters a, b, c, d,
and e in order, you could search a word list with the pattern
<code>/a.*b.*c.*d.*e/</code> and find ``absconded'' and ``ambuscade.'' That
has to be worth something.
<P></P>
However, there are times when you need to change things based on a
pattern match. Let's go back to our song list file. Whoever created it
entered all the artists' names in lowercase. When we display them on
our jukebox's screen, they'd look better in mixed case. How can we
change the first character of each word to uppercase?
<P></P>
The methods <a href="ref_c_string.html#sub"><code>String#sub</code></a> and <a href="ref_c_string.html#gsub"><code>String#gsub</code></a> look for a portion of
a string matching their first argument and replace it with their
second argument. <a href="ref_c_string.html#sub"><code>String#sub</code></a> performs one replacement, while
<a href="ref_c_string.html#gsub"><code>String#gsub</code></a> replaces every occurrence of the match. Both routines
return a new copy of the <code>String</code> containing the substitutions.
Mutator versions <a href="ref_c_string.html#sub_oh"><code>String#sub!</code></a> and <a href="ref_c_string.html#gsub_oh"><code>String#gsub!</code></a> modify the
original string.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>a = "the quick brown fox"</code></td>
</tr>
<tr>
<td valign="top"><code>a.sub(/[aeiou]/, '*')</code></td>
<td valign="top"></td>
<td valign="top"><code>"th* quick brown fox"</code></td>
</tr>
<tr>
<td valign="top"><code>a.gsub(/[aeiou]/, '*')</code></td>
<td valign="top"></td>
<td valign="top"><code>"th* q**ck br*wn f*x"</code></td>
</tr>
<tr>
<td valign="top"><code>a.sub(/\s\S+/, '')</code></td>
<td valign="top"></td>
<td valign="top"><code>"the brown fox"</code></td>
</tr>
<tr>
<td valign="top"><code>a.gsub(/\s\S+/, '')</code></td>
<td valign="top"></td>
<td valign="top"><code>"the"</code></td>
</tr>
</table>
<P></P>
<P></P>
The second argument to both functions can be either a <code>String</code> or
a block. If a block is used, the block's value is substituted into the
<code>String</code>.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>a = "the quick brown fox"</code></td>
</tr>
<tr>
<td valign="top"><code>a.sub(/^./) { $&.upcase }</code></td>
<td valign="top"></td>
<td valign="top"><code>"The quick brown fox"</code></td>
</tr>
<tr>
<td valign="top"><code>a.gsub(/[aeiou]/) { $&.upcase }</code></td>
<td valign="top"></td>
<td valign="top"><code>"thE qUIck brOwn fOx"</code></td>
</tr>
</table>
<P></P>
<P></P>
So, this looks like the answer to converting our artists' names. The
pattern that matches the first character of a word is <code>\b\w</code>---look for a word boundary followed by a word character. Combine
this with <code>gsub</code> and we can hack the artists' names.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>def mixedCase(aName)</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> aName.gsub(/\b\w/) { $&.upcase }</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td valign="top"><code>mixedCase("fats waller")</code></td>
<td valign="top"></td>
<td valign="top"><code>"Fats Waller"</code></td>
</tr>
<tr>
<td valign="top"><code>mixedCase("louis armstrong")</code></td>
<td valign="top"></td>
<td valign="top"><code>"Louis Armstrong"</code></td>
</tr>
<tr>
<td valign="top"><code>mixedCase("strength in numbers")</code></td>
<td valign="top"></td>
<td valign="top"><code>"Strength In Numbers"</code></td>
</tr>
</table>
<P></P>
<h3>Backslash Sequences in the Substitution</h3>
<P></P>
Earlier we noted that the sequences <code>\1</code>, <code>\2</code>,
and so on are
available in the pattern, standing for the <em>n</em>th group matched so
far. The same sequences are available in the second argument of
<code>sub</code> and <code>gsub</code>.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>"fred:smith".sub(/(\w+):(\w+)/, '\2, \1')</code></td>
<td valign="top"></td>
<td valign="top"><code>"smith, fred"</code></td>
</tr>
<tr>
<td valign="top"><code>"nercpyitno".gsub(/(.)(.)/, '\2\1')</code></td>
<td valign="top"></td>
<td valign="top"><code>"encryption"</code></td>
</tr>
</table>
<P></P>
<P></P>
There are additional backslash sequences that work in substitution
strings: <code>\&</code> (last match), <code>\+</code> (last matched group),
<code>\`</code> (string prior to match), <code>\'</code> (string after match), and
<code>\\</code> (a literal backslash).
It gets confusing if you want to include a literal backslash in a
substitution. The obvious thing is to write
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
str.gsub(/\\/, '\\\\')
</pre></td></tr></table>
<P></P>
Clearly, this code is trying to replace each backslash in <code>str</code>
with two. The programmer doubled up the backslashes in the replacement
text, knowing that they'd be converted to ``<code>\\</code>'' in syntax
analysis. However, when the substitution occurs, the regular
expression engine performs another pass through the string, converting
``<code>\\</code>'' to ``<code>\</code>'', so the net effect is to replace
each single backslash with another single backslash. You need to write
<code>gsub(/\\/, '\\\\\\\\')</code>!
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>str = 'a\b\c'</code></td>
<td valign="top"></td>
<td valign="top"><code>"a\b\c"</code></td>
</tr>
<tr>
<td valign="top"><code>str.gsub(/\\/, '\\\\\\\\')</code></td>
<td valign="top"></td>
<td valign="top"><code>"a\\b\\c"</code></td>
</tr>
</table>
<P></P>
<P></P>
However, using the fact that <code>\&</code> is replaced by the matched
string, you could also write
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>str = 'a\b\c'</code></td>
<td valign="top"></td>
<td valign="top"><code>"a\b\c"</code></td>
</tr>
<tr>
<td valign="top"><code>str.gsub(/\\/, '\&\&')</code></td>
<td valign="top"></td>
<td valign="top"><code>"a\\b\\c"</code></td>
</tr>
</table>
<P></P>
<P></P>
If you use the block form of <code>gsub</code>, the string
for substitution is analyzed only once (during the syntax pass) and
the result is what you intended.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>str = 'a\b\c'</code></td>
<td valign="top"></td>
<td valign="top"><code>"a\b\c"</code></td>
</tr>
<tr>
<td valign="top"><code>str.gsub(/\\/) { '\\\\' }</code></td>
<td valign="top"></td>
<td valign="top"><code>"a\\b\\c"</code></td>
</tr>
</table>
<P></P>
<P></P>
Finally, as an example of the wonderful expressiveness of combining
regular expressions with code blocks, consider the following code
fragment from the CGI library module, written by Wakou Aoyama. The code takes a string containing <font size="-2">HTML</font>
escape sequences and converts it into normal ASCII. Because it was
written for a Japanese audience, it uses the ``n'' modifier on the
regular expressions, which turns off wide-character processing. It
also illustrates Ruby's <code>case</code> expression, which we discuss
starting on page 83.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
def unescapeHTML(string)
str = string.dup
str.gsub!(/&(.*?);/n) {
match = $1.dup
case match
when /\Aamp\z/ni then '&'
when /\Aquot\z/ni then '"'
when /\Agt\z/ni then '>'
when /\Alt\z/ni then '<'
when /\A#(\d+)\z/n then Integer($1).chr
when /\A#x([0-9a-f]+)\z/ni then $1.hex.chr
end
}
str
end
<P></P>
puts unescapeHTML("1&lt;2 &amp;&amp; 4&gt;3")
puts unescapeHTML("&quot;A&quot; = &#65; = &#x41;")
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
1<2 && 4>3
"A" = A = A
</pre></td></tr></table>
<h3>Object-Oriented Regular Expressions</h3>
<P></P>
We have to admit that while all these weird variables are very
convenient to use, they aren't very object oriented, and they're
certainly cryptic. And didn't we say that everything in Ruby was an
object? What's gone wrong here?
<P></P>
Nothing, really. It's just that when Matz designed Ruby, he produced a
fully object-oriented regular expression handling system. He then made
it look familiar to Perl programmers by wrapping all these
$-variables on top of it all. The objects and classes are still there,
underneath the surface. So let's spend a while digging them out.
<P></P>
We've already come across one class: regular expression literals
create instances of class <code>Regexp</code> (documented beginning on page
366).
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>re = /cat/</code></td>
</tr>
<tr>
<td valign="top"><code>re.type</code></td>
<td valign="top"></td>
<td valign="top"><code>Regexp</code></td>
</tr>
</table>
<P></P>
<P></P>
The method <a href="ref_c_regexp.html#match"><code>Regexp#match</code></a> matches a regular expression
against a string. If unsuccessful, the method returns <code>nil</code>. On success,
it returns an instance of class <code>MatchData</code>, documented beginning
on page 340. And that <code>MatchData</code> object gives you
access to all available information about the match. All that good stuff
that you can get from the $-variables is bundled in a handy little
object.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>re = /(\d+):(\d+)/ # match a time hh:mm</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>md = re.match("Time: 12:34am")</code></td>
</tr>
<tr>
<td valign="top"><code>md.type</code></td>
<td valign="top"></td>
<td valign="top"><code>MatchData</code></td>
</tr>
<tr>
<td valign="top"><code>md[0] # == $&</code></td>
<td valign="top"></td>
<td valign="top"><code>"12:34"</code></td>
</tr>
<tr>
<td valign="top"><code>md[1] # == $1</code></td>
<td valign="top"></td>
<td valign="top"><code>"12"</code></td>
</tr>
<tr>
<td valign="top"><code>md[2] # == $2</code></td>
<td valign="top"></td>
<td valign="top"><code>"34"</code></td>
</tr>
<tr>
<td valign="top"><code>md.pre_match # == $`</code></td>
<td valign="top"></td>
<td valign="top"><code>"Time: "</code></td>
</tr>
<tr>
<td valign="top"><code>md.post_match # == $'</code></td>
<td valign="top"></td>
<td valign="top"><code>"am"</code></td>
</tr>
</table>
<P></P>
<P></P>
Because the match data is stored in its own object, you can keep the
results of two or more pattern matches available at the same time,
something you can't do using the $-variables. In the next example,
we're matching the same <code>Regexp</code> object against two strings. Each
match returns a unique <code>MatchData</code> object, which we verify by
examining the two subpattern fields.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>re = /(\d+):(\d+)/ # match a time hh:mm</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>md1 = re.match("Time: 12:34am")</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>md2 = re.match("Time: 10:30pm")</code></td>
</tr>
<tr>
<td valign="top"><code>md1[1, 2]</code></td>
<td valign="top"></td>
<td valign="top"><code>["12", "34"]</code></td>
</tr>
<tr>
<td valign="top"><code>md2[1, 2]</code></td>
<td valign="top"></td>
<td valign="top"><code>["10", "30"]</code></td>
</tr>
</table>
<P></P>
<P></P>
So how do the $-variables fit in? Well, after every pattern match,
Ruby stores a reference to the result (<code>nil</code> or a <code>MatchData</code>
object) in a thread-local variable (accessible using <code>$~</code>).
All the other regular expression variables are then derived from this
object. Although we can't really think of a use for the following
code, it demonstrates that all the other <code>MatchData</code>-related $-variables
are indeed slaved off the value in <code>$~</code>.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>re = /(\d+):(\d+)/</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>md1 = re.match("Time: 12:34am")</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>md2 = re.match("Time: 10:30pm")</code></td>
</tr>
<tr>
<td valign="top"><code>[ $1, $2 ] # last successful match</code></td>
<td valign="top"></td>
<td valign="top"><code>["10", "30"]</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>$~ = md1</code></td>
</tr>
<tr>
<td valign="top"><code>[ $1, $2 ] # previous successful match</code></td>
<td valign="top"></td>
<td valign="top"><code>["12", "34"]</code></td>
</tr>
</table>
<P></P>
<P></P>
Having said all this, we have to 'fess up. Andy and Dave normally use
the $-variables rather than worrying about <code>MatchData</code> objects. For
everyday use, they just end up being more convenient. Sometimes we just
can't help being pragmatic.
<p></p><hr><table bgcolor="#a03030" cellpadding="10" border="0" cellspacing="0"><tr><td width="33%" align="left"><a class="subheader" href="tut_containers.html">Previous <</a></td><td width="33%" align="center" valign="middle"><a class="subheader" href="index.html">Contents ^</a><br></td><td width="33%" align="right"><a class="subheader" href="tut_methods.html">Next ></a><br></td></tr></table><p></p><font size="-1">Extracted from the book "Programming Ruby -
The Pragmatic Programmer's Guide"</font><br><font size="-3">
Copyright
©
2000 Addison Wesley Longman, Inc. Released under the terms of the
<a href="http://www.opencontent.org/openpub/">Open Publication License</a> V1.0.
<br>
This reference is available for
<a href="http://www.pragmaticprogrammer.com/ruby/downloads/book.html">download</a>.
</font></body></html>
|