From: Frisco Del R. [mailto:[email protected]]
“why isn’t it 1 2 3 one three 1 3?”.
a delete (of some element) on an array will really be deleted, ergo, the
elements will rearrange/move to logically occupy that deleted space.
eg,
b=[1,2,3,4,5]
#=> [1, 2, 3, 4, 5]
b.delete 2
#=> 2
b
#=> [1, 3, 4, 5]
also, array#delete(obj) will delete all elements eql to obj. see below.
now, if you combine these behaviours while walking the array itself,
expect some surprises if you’re not ready
maybe if you show the index, ruby can help you, eg
a=[1,2,3,1,1,4]
#=> [1, 2, 3, 1, 1, 4]
a.each_with_index{|x,i| a.delete x if x==1; puts “#{i} → #{x}”}
0 → 1
1 → 3
2 → 4
#=> [2, 3, 4]
What if I wanted to make it so?
there are many better ways, but i will just modify your sample,
myArray = [1, 2, 3]
puts myArray
myArray.delete 2 #here i delete 2 first
myArray.each {|x|
if x == 1
then puts “one”
elsif x == 3
then puts “three”
end
}
puts myArray
1
2
3
one
three
1
3
kind regards -botp