In Ruby, you can remove the last element of an array and return the removed value in the following ways:
Using the pop
Method
The Ruby pop
method removes the last element from an array and returns the removed value. It mutates the original array, which means that the contents of the array are modified and its length
is changed. For example:
arr = [1, 2, 3, 4] removed_value = arr.pop puts removed_value #=> 4 puts arr.length #=> 3
If the pop
method is called on an empty array, it would return nil
:
puts [].pop #=> nil
Using the delete_at
Method
With the delete_at
method, you can specify the index at which you want to remove the array element. It mutates the original array, which means that the contents of the array are modified and its length is changed.
To remove the last element and return the removed value using the delete_at
method you can either specify array.length - 1
or -1
as the index. For example:
arr = [1, 2, 3, 4] removed_value = arr.delete_at(-1) puts removed_value #=> 4 puts arr.length #=> 3
Or, alternatively:
arr = [1, 2, 3, 4] removed_value = arr.delete_at(arr.length - 1) puts removed_value #=> 4 puts arr.length #=> 3
If the delete_at
method is called on an empty array, it would return nil
:
puts [].delete_at(-1) #=> nil
Hope you found this post useful. It was published . Please show your love and support by sharing this post.