Richard Jarram
Richard Jarram

Reputation: 1004

How to remove a single value from an array in Ruby?

I want to remove the first instance of the lowest value in the array.

arr = [1,2,3,1,2,3]
arr.reject {|i| i == arr.min}
#=> [2,3,2,3]

But my code removes all instances of the lowest value in the array. I want a result such that:

[...]
#=> [2,3,1,2,3]

What's the most elegant solution to this problem?

Upvotes: 2

Views: 235

Answers (3)

mechnicov
mechnicov

Reputation: 15248

You can use Enumerable#drop_while for this purpose

arr = [1,2,3,1,2,3]
arr.drop_while { |i| i == arr.min }
#=> [2, 3, 1, 2, 3]

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Just out of curiosity:

[1,2,3,1,2,3].tap { |a| a.delete_at a.each_with_index.min.last }
#⇒ [2, 3, 1, 2, 3]

Upvotes: 1

ggorlen
ggorlen

Reputation: 56865

On first blush, here are a couple of options:

arr.delete_at(arr.index(arr.min))
# or less readable but still valid
arr.delete_at arr.index arr.min    
arr.delete_at(arr.each_with_index.min[1])
# or
arr.delete_at(arr.each_with_index.min.pop)
# or
arr.delete_at(arr.each_with_index.min.last)

The first is less code and more readable but makes two passes through the list instead of one. I have doubts as to whether any other construct will surpass option #1 in elegance, as ugly as it may (or may not?) be.

Note that both choices crash on an empty array. Here's a safer version:

arr.delete_at arr.index(arr.min) || 0

Upvotes: 3

Related Questions