0

I'm working through the Ruby koans and have hit one that's really confusing me.

"one two-three".gsub(/(t\w*)/) { $1[0, 1] }
 => "one t-t"

However, when I modify the return array for the $1 variable, I get a confusing result.

"one two-three".gsub(/(t\w*)/) { $1[1, 2] }
 => "one wo-hr"

Given the first result, I'd expect the second bit of code to return "one w-h". Why are two characters being returned in the second instance?

1 Answer 1

2

You expect "one w-h" which would be the result of this:

"one two-three".gsub(/(t\w*)/) { $1[1, 1] }

[] is a method on string where a range can be provided like so:

str[start, length]

so the 2 in your code is actually the length (i.e. number of characters)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.