Passing References as Values

If Ruby is pass by value and the values it passes are references, then why doesn’t the code below change ans when I call set_it?

#! /usr/bin/env ruby

def set_it(data)
	data = 8888

if __FILE__ == $0

	ans = 1234
	p ans

I think I found the answer or part of the answer.

The reason is -> ans is a reference to an immutable object so when you change the value(from 1234 to 8888), you actually create a new immutable object with a value of 8888 that’s referenced by data. So the original reference ans is still referring to the immutable object 1234 and data will refer to the immutable object 8888.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs