Jobet De Lima
Jobet De Lima

Reputation: 11

arr.delete() vs arr.delete_at() in Ruby

I wrote the function below which accepts an array and returns a randomized version of it.

I've noticed that I sometimes end up with a nil element in randomizedArr when using list.delete(element) to remove an element from the array, but this does not happen when using list.delete_at(index) -- note that the latter is commented out in the below snippet. Am I missing something?

If there's a better way to do what I'm trying to achieve with this function then I would appreciate any suggestion. Thanks!

The array I'm passing to this function is a string array with ~2k elements. I'm passing in a clone of the original array so it doesn't become empty when the function is called. I'm using Ruby 2.1 on Windows 7.

def getRandomList(list)
    randomizedArr = Array.new()
    cnt = list.length
    while (cnt >= 1) do
        index = rand(cnt)
        prod = list[index]
        randomizedArr.push(prod)
        list.delete(prod)
        #list.delete_at(index)
        cnt = cnt - 1
    end

    if randomizedArr.include?(nil)
       puts "found nil element"
    end

    return randomizedArr
end #getRandomList()

Upvotes: 1

Views: 1036

Answers (2)

Brian Ruff
Brian Ruff

Reputation: 105

Referring to the Ruby documentation, this is what I found to answer your question:

#To delete an element at a particular index:
arr = [2, 3, 4, 5] #I added this bit
arr.delete_at(2) #=> 4
arr #=> [2, 3, 5]

#To delete a particular element anywhere in an array, use delete:

arr = [1, 2, 2, 3]
arr.delete(2) #=> 2
arr #=> [1,3]

All of that can be found here https://ruby-doc.org/core-2.4.1/Array.html

arr.delete(2) will remove any instance of 2 in an array while delete_at(2) only removes the third value in the array.

Upvotes: 2

archana
archana

Reputation: 1272

I am not sure why you need to put all that logic when you can randomize the list by list.shuffle.

Upvotes: 1

Related Questions