【问题标题】:Fixnum object does not change value after being increasedFixnum 对象增加后不改变值
【发布时间】:2018-11-25 14:41:57
【问题描述】:

刚开始学习Ruby,遇到了这2个函数:

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

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

当我尝试用 n = 5 增加(n)时

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

c的值在increase(n)中增加后不变

当我尝试使用 add_element 更改数组 arr = [1,2,3,4] 的内容时,arr 确实发生了变化。

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

那么如果 Ruby 中的一切都是对象,为什么 arr 会改变它的值,而 c(一个 Fixnum 对象)却不会改变它的值呢?

感谢您的想法。 :) 谢谢

【问题讨论】:

标签: ruby object addition fixnum


【解决方案1】:

Ruby 中有一些“特殊”的对象是不可变的。 Fixnum 是其中之一(其他是布尔值、nil、符号、其他数字)。 Ruby 也是按值传递的。

n = n + 1 不会修改n,它会在increase 的范围内重新分配一个局部变量。 由于Fixnum 不是可变的,因此没有任何方法可以用来更改其值,这与数组不同,数组可以使用多种方法进行变异,&lt;&lt; 就是其中之一。

add_element&lt;&lt; 显式修改传递的对象。如果将方法体更改为

array = array + [item]

那么第二个示例中的输出将是 array is [1, 2, 3, 4],因为它只是对局部变量的重新分配。

【讨论】:

    猜你喜欢
    • 2013-07-05
    • 1970-01-01
    • 2018-07-20
    • 2021-06-04
    • 1970-01-01
    • 2021-05-08
    • 2016-07-07
    • 2020-02-14
    • 1970-01-01
    相关资源
    最近更新 更多