In Progress
Unit 1, Lesson 21
In Progress

String Subscript Assignment

Video transcript & code

As befits its Perl heritage, Ruby makes string-munging delightfully easy. And quite a lot of the changes we might want to make to a String can be accomplished with a single method: the subscript assignment operator. (You might know it as the "indexing assignment operator", or simply "square brackets with an equals"). For instance, we can prepend text by assigning to the 0th element of a string and with a length of 0:

str = "String Subscript Assignment"
str[0,0] = "107 "
str                             # => "107 String Subscript Assignment"

Inserting text in the middle is a simple matter of changing the index argument:

str = "107 String Subscript Assignment"
str[4,0] = "Fun with "
str # => "107 Fun with String Subscript Assignment"

Or we can replace text given a starting point and a length:

str = "107 String Subscript Assignment"
str[0,3] = "XXX"
str                             # => "XXX String Subscript Assignment"

If we prefer we can use a range instead of index and length.

str = "107 String Subscript Assignment"
str[11..20] = "Index "
str                             # => "107 String Index Assignment"

Of course, these are all the kind of examples that look good in a book, and then when you go to use them in real life you realize that it means figuring out the index and length of the string you want to replace. Which is no fun.

Fortunately, String subscripts in Ruby are turbo-powered. As we've already seen in an earlier episode, we can extract part of a string by passing regex to the subscript:

'107 String Subscript Assignment'[/^\d{3}/] # => "107"

The really cool part is that we can modify the string this way as well!

str = '107 String Subscript Assignment'
str[/^\d{3}/] = 'XXX'
str                             # => "XXX String Subscript Assignment"

And not only that, a second argument for the regex group is also supported. Here we split the regex into groups for the episode number and title, and then assign to the title group:

str = '107 String Subscript Assignment'
str[/^(\d{3}) (.*)/, 2] = 'How cool is this??'
str                             # => "107 How cool is this??"

In case you're wondering, named regex groups are supported as well.

str = '107 String Subscript Assignment'
str[/^(?<number>\d{3}) (?<title>.*)/, :title] = "It's crazy cool!"
str                             # => "107 It's crazy cool!"

Well, I think that's enough String awesomeness for one day. I want to thank subscriber Austin Schneider for the comment that inspired this episode. Happy hacking!

Responses