Ruby 看到 String#[] 方法的一个用法

lululau · January 23, 2014 · Last by hooopo replied at January 23, 2014 · 2062 hits

例如:

str = "hello world"
result = $& if str =~ regex

可以用下面这量行代码代替:

result = str[regex]

另外:

result = $2 if str =~ /(\w+)\s(\w+)/

可以换成:

result = str[/(\w+)\s(\w+)/, 2]

这个不知道是不是太 out 了?

You need to Sign in before reply, if you don't have an account, please Sign up first.