Created
May 6, 2015 12:20
-
-
Save jamesmartin/bc7b390a9955c4e5015d to your computer and use it in GitHub Desktop.
Ruby is pass reference by value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Author
jamesmartin
commented
May 6, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment