Ruby字符串通过引用函数参数传递

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!.

这只是出于好奇 - 任何解释都会受到赞赏

Jör*_*tag 5

我知道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那样的纯函数式语言.

  • 我对这个问题的解释不同.OP多次讨论传递引用.他明确地问为什么`test1`无法证明传递引用,即使他被告知Ruby是传递引用.对此的正确答案是信任代码,这清楚地表明Ruby不是*不是*引用传递(否则OP的代码将按预期工作)而不是告诉他Ruby是传递参考的人.[这里有一个小片段,演示Ruby是按值传递,而不是按引用传递.](http://ideone.com/yWbRGE) (2认同)