gpt4 book ai didi

Ruby attr_accessor 包装器返回 nil。

转载 作者:行者123 更新时间:2023-12-02 21:21:16 24 4
gpt4 key购买 nike

我有一个简单的类,并且正在转置一个二维数组,如下所示:

class Group
attr_accessor :group_array
def initialize
@group_array = []
end

...

def shuffle_groups!
new_groups = group_array.transpose
group_array = new_groups
end

end

但是,当我尝试像这样在一行中设置新的组数组时:

def shuffle_groups!
group_array = group_array.transpose
end

我得到:

undefined method `transpose' for nil:NilClass

为什么这不起作用?

最佳答案

让解释器清楚您正在调用访问器方法,而不是创建局部变量。

class Group

attr_accessor :group_array

def initialize
@group_array = [%w(1 2 3), %w(4 5 6)]
end

def shuffle_groups!
new_groups = self.group_array.transpose
self.group_array = new_groups
end

def shuffle_groups_2!
self.group_array = self.group_array.transpose
end

end

g = Group.new
p g.group_array
# [["1", "2", "3"], ["4", "5", "6"]]
g.shuffle_groups!
p g.group_array
# [["1", "4"], ["2", "5"], ["3", "6"]]
g.shuffle_groups_2!
p g.group_array
# [["1", "2", "3"], ["4", "5", "6"]]

这两种方法都可以正常工作。

关于Ruby attr_accessor 包装器返回 nil。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27428099/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com