jrh*_*e17 4 ruby pass-by-reference
Ruby noob在这里
我知道ruby确实通过函数参数的引用传递
但是,我感觉这与传统的c/c ++风格略有不同
示例代码:
def test1(str)
str += ' World!'
end
def test2(str)
str << ' World!'
end
str = 'Hello'
test1(str)
p str # Hello
test2(str)
p str # Hello World!
Run Code Online (Sandbox Code Playgroud)
如果我在c/c ++中使用引用,我希望test1
也会返回Hello World!
.
这只是出于好奇 - 任何解释都会受到赞赏
我知道ruby确实通过函数参数的引用传递
Ruby始终是严格按值传递的.Ruby中没有任何pass-by-reference.
这只是出于好奇 - 任何解释都会受到赞赏
为什么你的代码片段没有显示你期望通过引用传递的结果的简单解释是Ruby不是通过引用传递的.它是按值传递的,您的代码段证明了这一点.
这是一个小片段,它表明Ruby实际上是按值传递而不是通过引用传递:
#!/usr/bin/env ruby
def is_ruby_pass_by_value?(foo)
foo << <<~HERE
More precisely, it is call-by-object-sharing!
Call-by-object-sharing is a special case of pass-by-value,
where the value is always an immutable pointer to a (potentially mutable) value.
HERE
foo = 'No, Ruby is pass-by-reference.'
return
end
bar = ['Yes, of course, Ruby *is* pass-by-value!']
is_ruby_pass_by_value?(bar)
puts bar
# Yes, of course, Ruby *is* pass-by-value!,
# More precisely, it is call-by-object-sharing!
# Call-by-object-sharing is a special case of pass-by-value,
# where the value is always an immutable pointer to a (potentially mutable) value.
Run Code Online (Sandbox Code Playgroud)
然而Ruby 确实允许对象的变异,它不是像Haskell或Clean那样的纯函数式语言.
归档时间: |
|
查看次数: |
1906 次 |
最近记录: |