Envision, Create, Share

Welcome to HBGames, a leading amateur game development forum and Discord server. All are welcome, and amongst our ranks you will find experts in their field from all aspects of video game design and development.

Delete one of the Same item in an array?.

Well, the title says all:

I have:
Code:
Array = ['Object 1', 'Object 2', 'Object 1', 'Object 2', 'Object 3']
and when i use:
Code:
Array.delete('Object 1')
It delete all the 'Object 1' objects, and I want to delete only 1 of them.

Is there a method in the array class to do this?

Thanks :thumb:
 
Near":3gk4agns said:
I am not sure, but can't you just do this:
Ruby:
 

for i in Array

  if i == 'Object 1'

    Array.delete(i)

  end

end

 

that will delete them all too.

Ruby:
 

for i in 0...Array.size

  if Array[i] == 'Object 1'

    Array.delete_at(i)

    break

  end

end

 
 
Are you trying to delete the first instance of that value in the array? Or a very specific instance of that value? If you just want to delete the first, try this:

Code:
if Array.include?('Object 1')

  i = Array.index('Object 1')

  Array.delete_at(i)

end

Edit: Brew, which is more efficient? My method or yours? I mean, It probably wouldn't make much of a difference, but I was wondering...
 

Zeriab

Sponsor

Most likely your method Glitchfinder since the methods you use are implemented in C.
Otherwise it would be Brew's version since .include? and .index both search through the array. That is, you search through the array twice where Brew only does it once.

If you really want to know you can always build up a test case and test it out. Maybe an conclusion is that the speed difference is insignificant.

*hugs*
- Zeriab
 

Thank you for viewing

HBGames is a leading amateur video game development forum and Discord server open to all ability levels. Feel free to have a nosey around!

Discord

Join our growing and active Discord server to discuss all aspects of game making in a relaxed environment. Join Us

Content

  • Our Games
  • Games in Development
  • Emoji by Twemoji.
    Top