Ruby:Substring

From Progzoo
Jump to: navigation, search

Ruby uses several notations for retrieving a substring from a string.

One way is to index the string using a Range. It is written like this string[a..b] or this string[a...b].

[5..6] extracts characters (takes a slice) from position 5 to position 6 (including position 6). [5...7] extracts characters (takes a slice) from position 5 to just before position 7.

Another way is to specify the starting index and the length. It is written like this string[a,b].

[5,2] extracts characters (takes a slice) starting from position 5, with length 2.

Note that this can also be used to get a slice from array like structures.

0 1 2 3 4 5 6 7 8 9 10 11 12
O n e t w o t h r e e
f o u r f i v e s i x



[Font] [Default] [Show] [Resize] [History] [Profile]

Use [a..-1] to get part of a string.

[5..-1] extracts characters form position 5 to the end (-1 indicates the last character in the string).

0 1 2 3 4 5 6 7 8 9 10 11 12
O n e t w o t h r e e
f o u r f i v e s i x



[Font] [Default] [Show] [Resize] [History] [Profile]

Use [a] to get a single character from a string.

[5] extracts the character form position 5.

Caution: In Ruby version 1.8, a "character" is represented as an integer with the character code of the character. Hence indexing a string will evaluate to an integer. In Ruby version 1.9, the semantics has changed such that a "character" is represented as a string of length 1 (same as Python). Hence indexing a string will evaluate to a string. In both cases, you can use the .chr method to go from a "character" to a length-1 string. (So string[5].chr is always equivalent to string[5,1] on both versions of Ruby.)

0 1 2 3 4 5 6 7 8 9 10 11 12
O n e t w o t h r e e
f o u r f i v e s i x



[Font] [Default] [Show] [Resize] [History] [Profile]