DEV Community

[Comment from a deleted post]
Collapse
 
briankephart profile image
Brian Kephart • Edited

This is tricky to think about in Ruby because IMO the pass-by-value/reference distinction comes from languages where these are both possible as different behaviors, and Ruby is not really designed to be thought of in that way. Ruby is technically ALWAYS pass-by-value, but all variables and arguments are references to objects. Confused yet?

Pass by value: You give your friend a toy (pass your method an argument). It's theirs now, and you don't play with it anymore. Maybe you have an identical toy at home, but whatever your friend does to their toy doesn't affect yours.

Pass by reference: You tell your friend where your toy is. Now, whatever they do to the toy (pose it, cut its hair, whatever), you will find the toy as they left it next time you play with it.

How Ruby works: You give your friend a treasure map (a reference to an object). You can pass your friend a treasure map just like another one you have, and changes to their map don't affect yours. If they redraw their map, yours doesn't change.

def change(str)
  str = 'Nothing here!'
end

var = 'Treasure'
change(var) # => 'Nothing here!'
var         # => 'Treasure'

But if they follow the map to the treasure and mess with it...

def change(str)
  str << ' used to be here :('
end

var = 'Treasure'
change(var) # => "Treasure used to be here :("
var         # => "Treasure used to be here :("

More here.