From: Dave Thomas Date: 2000-10-21T15:25:00+09:00 Subject: [ruby-talk:5728] Re: String#slice surprise "Guy N. Hurst" writes: > Suppose $string="Hello there" > > In Perl (and PHP), > > substr($string, 4, 1) == "o" > and substr($string, 4, 3) == "o t" > but substr($string, 4) == "o there" > > In other words, if you leave out the third parameter ('length'), > it just goes to the end of the string. Makes perfect sense, and > is balanced well by the functionality to extract a single character. > > In Ruby, > > string.slice(4,1) == "o" > and string.slice(4,3) == "o t" > but string.slice(4) == 111 # (!) Ruby gives you the option of returning a single character as either a string or as a byte. This flexibility comes in vry handy when you're dealing with strings that contain binary data. > What is worse, if I *do* wish to get a substring from a starting > position to the end, it seems I have to use an embedded function: > > string.slice(4..string.size) == "o there" Negative indices count from the end of a string string = "hello there" string[4..-1] # => "o there" string[-4, 2] # => "he" string[-6..-2] # => " ther" Regards Dave