Ruby pass by value or reference, which one of them is used when object/variables are passed to the functions. This tutorial will help you understand how passing value/objects in Ruby work.
Pass by Value:
Let us see the interpretation of this example below,
The value of variable number is not modified by the function test_ruby_function.
The function test_ruby_function does not have separate copy of ‘number’ object.
The value of reference of object holding ‘number’ is sent to the function test_ruby_function
Yes, Ruby methods use Pass by Value, and not Pass by Reference - But, value of the reference of object is passed to the Ruby Methods
Passign value of a reference:
- It shows that original name string points to the same object even after the function call sample_function which tries to modify the value of the name.
- When we try to assign new value to the variable passed to function, it changes reference to new memory location. Thus, old reference and it’s value are remained intact.
- Thus, when we pass values to ruby function - we can change value of the variable keeping the same reference to the object. But when we can not replace it entirely by a new object.
- Mostly, Ruby uses pass by value. But, ruby passes value of reference of the object that needs to be shared between the function.
- Ultimately, ruby uses pass by object sharing.
If you are still not clear how passing variables are shared amongst functions in Ruby or what is Ruby Pass by value/ Pass by Reference then you can refer this StackOverflow answer for more information.
You can let us know through comments if you have any feedback/difficulty understanding this.
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox