PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 6, 2022

[FIXED] Why can you change the value of a local variable in Ruby in a function using another method but not with an assignment operator?

 July 06, 2022     pass-by-reference, pass-by-value, ruby, variables     No comments   

Issue

I'm trying to understand the concept of Ruby as a pass-by-reference-value language. Using an example I found on this site...

def uppercase(value)
  value.upcase!
end

name = 'William'
uppercase(name)
puts name

we get the output "WILLIAM". So value and name are both pointing at the same object, which is initially holding a value of "William" and then .upcase changes it to "WILLIAM". I would understand this as pass-by-reference.

But then if I change .upcase to =:

def uppercase2(value)
  value = "WILLIAM"
end

name = 'William'
uppercase2(name)
puts name

The output becomes "William". Which is pass by value.

Why does an assignment operator make the difference in how a variable is treated in Ruby?


Solution

The key here is that you can never change a Ruby object's core self, once it has been created it will always be the same object until garbage collected and destroyed. It is only possible to alter properties of the object.

You can, however, change variables or object references such as instance variables, constants, attr_accessor properties among other things.

So in this case:

def uppercase2(value)
  value = "WILLIAM"
end

This reassigns the value local variable. It does nothing to the original object.

If you want to replace that text you need to use methods on the object to effect it, if supported. In this case there is a method:

def uppercase2(value)
  value.replace("WILLIAM")
end

These are generally termed in-place modifications as in the object itself is manipulated rather than swapped for another object.



Answered By - tadman
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing