0

I'm getting the following error when I run my code from my rspec file:

pad pads element to the end of an array

Failure/Error: expect(pad(array,array.length + pad_size, 'apple')).to     eq(array+Array.new(pad_size, 'apple')) 

expected: ["apple", "apple", "apple",...]

my current code is:

def pad!(array, min_size, value = nil) #destructive

    difference = min_size-array.length

    difference.times {array << value} 

    array
end

def pad(array, min_size, value = nil) #non-destructive

    difference = min_size-array.length

    difference.times {array << value} 

    array.clone  

end    

Can anyone help me figure out why it's giving me this error message? I thought that {array << value } was adding new elements to the end of my array inputs. Thank you!

2
  • can you also give the input data array, so that I can run and debug ? Commented Apr 6, 2015 at 17:24
  • Your new_array = array.clone should go up. Commented Apr 6, 2015 at 17:26

1 Answer 1

3

Your non-destructive version is actually destructive. What you want is probably this:

def pad(array, min_size, value = nil)
  pad!(array.clone, min_size, value)
end

There's no point in implementing the same behaviour twice. Make one bridge off of the other.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you @tadman I'm days new to Ruby, I was trying to figure out a way to run what you had here, but kept running into errors in my powershell because I was trying to do array.clone.pad!(min_size, value), I see my issue now!
No trouble at all. If you're feeling adventurous, you can always make these methods part of Array so you can call things like array.pad(...) instead. That can clean up your code a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.