Fixnum object does not change value after being increased

111 views Asked by At

I just started learning Ruby, and encounterd this 2 functions:

def increase(n)
    n = n + 1
    return n
end

def add_element(array, item)
    array << item
end

When I tried increase(n) with n = 5

c = 5
p10.increase(c)
print("c is #{c}\n")
print("c.class is #{c.class}\n")
--> c is 5
--> c.class is Fixnum

Value of c does not change after being increased inside increase(n)

When I tried to change the content of an array arr = [1,2,3,4] with add_element, arr does change.

arr = [1, 2, 3, 4]
p10.add_element(arr, 5)
print("array is #{arr}\n")
--> array is [1, 2, 3, 4, 5]

So if everything in Ruby is object, why arr changes its value, but c ( a Fixnum object ) does not change its value?

Your thought is appreciated. :) Thanks

1

There are 1 answers

0
Marcin Kołodziej On

There are "special" objects in Ruby that are not mutable. Fixnum is one of them (others are booleans, nil, symbols, other numerics). Ruby is also pass by value.

n = n + 1 does not modify n, it reassigns a local variable in increase's scope. Since Fixnum isn't mutable, there is no method you could use to change its value, unlike an array, which you can mutate with multiple methods, << being one of them.

add_element explicitly modifies the passed object with <<. If you change the method body to

array = array + [item]

then the output in your second example will be array is [1, 2, 3, 4] as it's a mere reassignment of a local variable.