I'm trying to translate the following code into ruby:
public void discardWeapon(Weapon w){
if(!weapons.isEmpty()){
boolean discarded = false;
Iterator<WeaponType> it = weapons.iterator();
while(it.hasNext() && !discarded){
WeaponType wtaux = it.next();
if(wtaux == w.getWeaponType()){
it.remove();
discarded = true;
}
}
}
}
But, when it comes to the while loop, I can't really find a practical way to do it in ruby. I've got the following structure so far:
def discardWeapon(w)
if([email protected]?)
discarded = false
@weapons.each do |wtaux|
end
end
end
But, how can I check my condition is met when using the .each iterator? Thanks in advance.
I am not sure if I read your Java code correctly, but it feels to me like you have an instance variable @weapons that holds an array of weapons and you want to discard one instance of a weapon w from that list.
def discard_weapon(weapon)
index = @weapons.index(weapon)
@weapons.delete_at(index) if index
end
Array#index returns the index of the first match. And Array#delete_at deletes the element at the index when there was an element found.
When it is possible that the same weapon is included in the array multiple times and you want to discard all matching weapons then you can use the following one-liner:
def discard_weapon(weapon)
@weapons.delete(weapon)
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With