Stefan Ivanov
Stefan Ivanov

Reputation: 115

How do I fix the wrong number of brackets in a generated array?

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

Upvotes: 0

Views: 64

Answers (4)

maerics
maerics

Reputation: 156384

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?

Upvotes: 1

DGM
DGM

Reputation: 26979

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

try:

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

Upvotes: 1

Hauleth
Hauleth

Reputation: 23556

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

Upvotes: 1

sepp2k
sepp2k

Reputation: 370102

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.

Upvotes: 1

Related Questions