Iterating and Incrementing Strings in Ruby - Incrementing Strings (Page 4 of 6 )
The Ruby String class has several methods that let you produce successive strings—that is, strings that increment, starting at the rightmost character. You can increment strings with next and next!(orsuccandsucc!). I prefer to usenext. (The methods ending in!make in-place changes.) For example:
"a".next [or] "a".succ # => "b"
Remember,nextincrements the rightmost character:
"aa".next # => "ab"
It adds a character when it reaches a boundary, or adds a digit or decimal place when appropriate, as shown in these lines:
"z".next # => "aa" # two a's after onez "zzzz".next # => "aaaaa" # five a's after four z's "999.0".next # => "999.1" # increment by .1 "999".next # => "1000" # increment from 999 to 1000
We’re not just talking letters here, but any character, based on the character set in use (ASCII in these examples):
" ".next # => "!"
Chain calls ofnexttogether—let’s try three:
"0".next.next.next # => "3"
As you saw earlier,nextworks for numbers represented as strings as well:
"2007".next # => "2008"
Or you can get it to work when numbers are not represented as strings, though the method will come from a different class, notString. For example:
2008.next # => 2009
Instead of fromString, this call actually uses thenextmethod fromInteger. (TheDate,Generator,Integer, andString classes all havenext methods.)
You can even use a character code viachrwithnext:
120.chr # => "x" 120.chr.next # => "y"
Theuptomethod fromString, which uses a block, makes it easy to increment. For example, this call touptoprints the English alphabet:
"a".upto("z") { |i| print i } # => abcdefghijklmnopqrstuvwxyz
You could also do this with aforloop and an inclusive range:
for i in "a".."z" print i end
You decide what’s simpler. Theforloop takes only slightly more keystrokes (29 versus 31, including whitespace). But I likeupto.