How to remove the first occurrence of something?
a=[1,2,3,4]
a.find!{ |e| a==2 } #=> 2
But there is no #find!, how to define it? My solutions seem unduly
complex.
Thanks,
T.
How to remove the first occurrence of something?
a=[1,2,3,4]
a.find!{ |e| a==2 } #=> 2
But there is no #find!, how to define it? My solutions seem unduly
complex.
Thanks,
T.
On 2/29/08, 7stud – [email protected] wrote:
T.
end
end
Why not just…
arr = [1, 2, 2, 2, 3]
arr.delete_at(arr.index(2))
arr => [1, 2, 2, 3]
Christopher
7stud – wrote:
arr.each_with_index do |elmt, i|
if elmt == 2
arr.delete_at(i)
break
end
end
If you’re going that far, why not just
arr.delete_at(arr.index(2))
(Of course that’s limited to #== comparisons. Maybe Array#index should
take a block…)
Trans wrote:
How to remove the first occurrence of something?
a=[1,2,3,4]
a.find!{ |e| a==2 } #=> 2But there is no #find!, how to define it? My solutions seem unduly
complex.Thanks,
T.
More complex than the following?
arr = [1, 2, 3, 2, 2, 2]
arr.each_with_index do |elmt, i|
if elmt == 2
arr.delete_at(i)
break
end
end
p arr
[1, 3, 2, 2, 2]
On Sat, 2008-03-01 at 10:15 +0900, 7stud – wrote:
arr.each_with_index do |elmt, i|
if elmt == 2
arr.delete_at(i)
break
end
end
This won’t work in 1.9: “RuntimeError: can’t modify array during
iteration”.
Best,
Andre
From: Joel VanderWerf [mailto:[email protected]]
of course, we agree, that is why matz put it in 1.9
irb(main):011:0> RUBY_VERSION
=> “1.9.0”
irb(main):012:0> a
=> [“this”, “is”, “a”, “test”]
irb(main):013:0> a.index{|e| e=~ /^is/}
=> 1
irb(main):014:0> a
=> [“this”, “is”, “a”, “test”]
irb(main):015:0> a.delete_at(a.index{|e| e=~ /^is/})
=> “is”
irb(main):016:0> a
=> [“this”, “a”, “test”]
and 1.9 is fast
kind regards -botp
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs