Ruby attr_accessor wrapper returning nil.

2k Views Asked by At

I have a simple class and am transposing a two dimensional array like so:

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

However, when I try to set the new group array in one line like so:

def shuffle_groups!
    group_array = group_array.transpose
end

I get:

undefined method `transpose' for nil:NilClass

Why does this not work?

1

There are 1 best solutions below

3
On BEST ANSWER

Make it clear to the interpreter you are calling the accessor method, and not creating a local variable.

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"]]

Both of those methods work fine.