Skip to content

Instantly share code, notes, and snippets.

@jamesmartin
Created May 6, 2015 12:20
Show Gist options
  • Select an option

  • Save jamesmartin/bc7b390a9955c4e5015d to your computer and use it in GitHub Desktop.

Select an option

Save jamesmartin/bc7b390a9955c4e5015d to your computer and use it in GitHub Desktop.
Ruby is pass reference by value
def value_and_identity(object)
"(Value: #{object.inspect}, ID: #{object.object_id})"
end
def increment(val)
puts "---> #increment received argument #{value_and_identity(val)}"
result = val += 1
puts "---> 'result' is #{value_and_identity(result)}"
result
end
def change_string(str)
puts "---> #change_string received argument 'str': #{value_and_identity(str)}"
str << "Mutating this string! "
str << "And the outside world will see it..."
puts "---> 'str' is #{value_and_identity(str)}"
str = "...because objects in Ruby are Reference types" # Their value is a reference to another object
end
if __FILE__ == $0
puts "Ruby is 'pass reference by value'..."
puts "Example 1:"
array_a = [0]
puts [value_and_identity(array_a)]
array_b = array_a
puts [value_and_identity(array_a), value_and_identity(array_b)]
array_b << 1
puts [value_and_identity(array_a), value_and_identity(array_b)]
puts "\n\n"
puts "Example 2:"
val = 1
puts "-> Passing variable 'val' #{value_and_identity(val)} to #increment function..."
increment(val)
puts "-> after calling #increment with 'val': #{value_and_identity(val)}"
puts "\n\n"
puts "... Except all object values are references..."
puts "\n\n"
puts "Example 3:"
str = "hello"
puts "-> Passing variable 'str' #{value_and_identity(str)} to #change_string function..."
change_string(str)
puts "-> after calling #change_string with 'str': #{value_and_identity(str)}"
puts "\n\n"
puts "If you want simpler Ruby programs, prefer immutability."
end
@jamesmartin
Copy link
Copy Markdown
Author

$ ruby value_or_reference.rb
Ruby is 'pass reference by value'...
Example 1:
(Value: [0], ID: 2156900320)
(Value: [0], ID: 2156900320)
(Value: [0], ID: 2156900320)
(Value: [0, 1], ID: 2156900320)
(Value: [0, 1], ID: 2156900320)


Example 2:
-> Passing variable 'val' (Value: 1, ID: 3) to #increment function...
---> #increment received argument (Value: 1, ID: 3)
---> 'result' is (Value: 2, ID: 5)
-> after calling #increment with 'val': (Value: 1, ID: 3)


... Except all object values are references...


Example 3:
-> Passing variable 'str' (Value: "hello", ID: 2156899040) to #change_string function...
---> #change_string received argument 'str': (Value: "hello", ID: 2156899040)
---> 'str' is (Value: "helloMutating this string! And the outside world will see it...", ID: 2156899040)
-> after calling #change_string with 'str': (Value: "helloMutating this string! And the outside world will see it...", ID: 2156899040)


If you want simpler Ruby programs, prefer immutability.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment