DDDD
DDDD

Reputation: 3940

Array drop not saving

I have an instance variable that is an array. I want to remove the last two elements and the first three elements. Then I want to remove any that are valued = nil.

The drop is not saving though:

@attribute_names = []

<% @attribute_names = word.attribute_names %>
  <% @attribute_names.pop(2) %>
  <% @attribute_names.drop(3) %>
<td> <%= @attribute_names %> </td>

The pop is working but the drop is not working in the table data. Why is that?

Upvotes: 0

Views: 81

Answers (2)

Uri Agassi
Uri Agassi

Reputation: 37409

The method pop removes the element from the array, and returns it.

The method drop returns a new array without the X first elements - the receiver stays the same!

If you want to drop the first three elements of the receiver, you can use slice!:

a = [1, 2, 3, 4, 5, 6]
a.pop
# => 6
a
# => [1, 2, 3, 4, 5]
a.drop(3)
# => [4, 5]
a
# => [1, 2, 3, 4, 5]
a.slice!(0, 3)
# => [1, 2, 3]
a
# => [4, 5]

Upvotes: 2

Wayne Conrad
Wayne Conrad

Reputation: 107999

Array#[range] will do it:

@attribute_names = @attribute_names[2...-3]

Consider moving this logic into a helper method, where it can be given a name that explains why some elements are being skipped.

Upvotes: 1

Related Questions