Lahiru
Lahiru

Reputation: 2664

pass reference of primitive data types to functions in ruby

By default ruby passes copy of primitive values and references for object types. How to pass references of primitive type variables (ex: integers, floating points) into a function?

Upvotes: 1

Views: 425

Answers (2)

Agis
Agis

Reputation: 33646

Ruby does not work that way. There are no pointers, if that's what you mean and it . Arguments are passed by value, but these values are themselves references to objects in memory.

What you call "primitives" (eg. the value 1) are in fact immutable objects in Ruby so it would not make sense to have pointers to them. Passing a variable containing that object is the way to go.

I'm curious about what you want to achieve though.

Upvotes: 3

Stefan
Stefan

Reputation: 114218

Ruby doesn't pass arguments by reference:

def change(x)
  x = 2  # this assigns to a local variable 'x'
end

a = 1
change(a)
a #=> 1

You could pass a mutable object instead, e.g. a hash "containing" an integer:

def change(h)
  h[:x] = 2
end

h = {x: 1}
change(h)
h[:x] #=> 2

Upvotes: 4

Related Questions