all jazz
all jazz

Reputation: 2017

mapping array in specific interval / range

Why won't mapping change the array with this function:

array[1..5].map! { |part| "<p>#{part}</p>" }

I know that I could just assign array[1..5] to the result, but there's probably some better way to do it.

How should I do it?

Upvotes: 0

Views: 350

Answers (2)

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369458

Well, it does change the array. You're just not seeing it, because you never assign the array to anything, so it will be immediately garbage collected again.

Upvotes: 3

Ian Bishop
Ian Bishop

Reputation: 5205

[](*args)

Returns a new array populated with the given objects.

Source

So, you're actually applying map! to a new array of just that range, not the actual array.

Assignment is necessary.

Upvotes: 4

Related Questions