0

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

dia099
  • 9
  • 1
  • Not all objects are mutable. Numbers, as you found out, are not. If they were, the outcome of `1+2` could be anything. – steenslag Nov 25 '18 at 16:54
  • See here: https://stackoverflow.com/questions/28083650/why-cant-i-overwrite-self-in-the-integer-class and warning: constant ::Fixnum is deprecated: https://stackoverflow.com/a/21411269/5239030 – iGian Nov 25 '18 at 17:28
  • What is `p10`? . – sawa Nov 26 '18 at 04:43

1 Answers1

4

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.

Marcin Kołodziej
  • 5,253
  • 1
  • 10
  • 17