0

When I call next() I have an extraneous [] in @current. How can I fix this?

class Result    
  attr_accessor :current

  def initialize(*previous)
    @current = previous
    p @current
  end

  def next()
    res = Result.new(@current)
  end
end

res = Result.new([2,2], [3,3], [4,4])
nextArray = res.next
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Stefan Ivanov
  • 115
  • 2
  • 5

4 Answers4

1

You'll need to do Result.new(*@current) with an asterisk before the previous, so the array gets "splatted" back into a list of arguments, so you're calling Result.new with three arguments rather than one array containing three arrays.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
1

It's cause *previous is an array. So if you call Result.new @current it's wrapped in next array and so on.

Hauleth
  • 22,873
  • 4
  • 61
  • 112
1

Your first call has 3 parameters, whereas the call in next() has only one.

try:

def next()
  res = Result.new(*@current)
end
DGM
  • 26,629
  • 7
  • 58
  • 79
1

Try expanding the array in @current as separate arguments to the constructor (instead of as a single array argument):

def next
  res = Result.new(*@current)
end

See also this question explaining that asterisk operator: What does the (unary) * operator do in this Ruby code?

Community
  • 1
  • 1
maerics
  • 151,642
  • 46
  • 269
  • 291