Sunday, April 22, 2007

substr in Ruby

Some times you want to extract the characters from a certain offset within a string. In Perl and PHP you have the substr function, e.g.


$str = "Hello world";
substr($str, 6); # --> "world"


In Ruby, this is done using the slice method of the String class. However, slice works a little different; slice is really an alias to [], so:


str = "Hello world"
str.slice(6) # --> 119
str[6] # --> 119

This may come as a surprise if you are used to substr; this returns the value of the character and not the rest of the string. Instead, we can do the same using negative indices, since negative indices count from the end of the string:


str.slice(6..-1) # --> "world"
str[6..-1] # --> "world"

No comments: