Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby string pass by reference function parameter

Tags:

Ruby noob here

I understand ruby does pass by reference for function parameters

However, I am getting the feeling this is slightly different from conventional c/c++ style pass by reference

Sample code:

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!

I would expect test1 to also return Hello World! if I were using references in c/c++.

This is simply out of curiosity -- any explanations would be appreciated

like image 536
jrhee17 Avatar asked Oct 12 '16 09:10

jrhee17


1 Answers

I understand ruby does pass by reference for function parameters

Ruby is strictly pass-by-value, always. There is no pass-by-reference in Ruby, ever.

This is simply out of curiosity -- any explanations would be appreciated

The simple explanation for why your code snippet doesn't show the result you would expect for pass-by-reference is that Ruby isn't pass-by-reference. It is pass-by-value, and your code snippet proves that.

Here is a small snippet that demonstrates that Ruby is, in fact, pass-by-value and not pass-by-reference:

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

Ruby does however allow mutation of objects, it is not a purely functional language like Haskell or Clean.

like image 115
Jörg W Mittag Avatar answered Sep 23 '22 16:09

Jörg W Mittag