Ruby函数传参数方法、正则表达式结果的生命期
作者:半瓶墨水 链接:http://www.2maomao.com/blog/ruby-func-param-regex-results-life/
一直都对Ruby中如何写一个带感叹号的函数感到模糊不清。
一开始有点儿昏头,认为加上感叹号就改了,神智清醒的时候一想就不对。
后来查资料,发现Ruby传参数都是传引用,如果你在函数里面对该引用调用了带感叹号的函数,那就改了,否则,就没改。
以下面的这个例子来说明吧:
def fake_modify!(str)
str = str.upcase
end
def real_modify1!(str)
str[0] = 65.chr
end
def real_modify2!(str)
str.upcase!
end
str = "abcde"
puts "original :" + str
fake_modify!(str)
puts "fake_modify:" + str #abcde
real_modify1!(str)
puts "real_modify1:" + str #Abcde
real_modify2!(str)
puts "real_modify2:" + str #ABCDE
str = str.upcase
end
def real_modify1!(str)
str[0] = 65.chr
end
def real_modify2!(str)
str.upcase!
end
str = "abcde"
puts "original :" + str
fake_modify!(str)
puts "fake_modify:" + str #abcde
real_modify1!(str)
puts "real_modify1:" + str #Abcde
real_modify2!(str)
puts "real_modify2:" + str #ABCDE
另外做了一个小测试,证明正则表达式的匹配结果$` $& $‘的临时性,虽然用的是$,却不是全局的:
def test_regexp_result
"abcde" =~ /cd/
puts $` + "<<" + $& + ">>" + $' #ab<<cd>>e
end
test_regexp_result
puts $` + "<<" + $& + ">>" + $ #ERROR: test.rb:6: undefined method `+' for nil:NilClass
"abcde" =~ /cd/
puts $` + "<<" + $& + ">>" + $' #ab<<cd>>e
end
test_regexp_result
puts $` + "<<" + $& + ">>" + $ #ERROR: test.rb:6: undefined method `+' for nil:NilClass
标签:[tag]Ruby, test[/tag]
比这篇新的: Ruby 中文、Unicode处理上的问题一例
比这篇旧的: Ruby语言的龌龊之处 - “抢床”问题
相关文章:
其他文章:
比这篇旧的: Ruby语言的龌龊之处 - “抢床”问题
相关文章:
- Windows下的用vim编辑javascript: ctags, taglist, javscript设置
- 两个Ruby小函数:URLDecode/URLEncode
- Ruby语言的龌龊之处 - ARGV自动展开
其他文章:
555,本篇现在一条评论也没有,雁过留声,人过留名,各位乡亲父老,有钱的捧个钱场,没钱的捧个人场......
发表评论
Additional comments powered by BackType


