简体   繁体   中英

Using array results from ruby gsub method and a match block

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 wh". Why are two characters being returned in the second instance?

You expect "one wh" 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 (ie number of characters)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM