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.
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]
--
Posted via http://www.ruby-forum.com/\.
Why not just...
arr = [1, 2, 2, 2, 3]
arr.delete_at(arr.index(2))
arr => [1, 2, 2, 3]
Christopher
On 2/29/08, 7stud -- <bbxx789_05ss@yahoo.com> wrote:
Trans wrote:
> 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.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
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...)
--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407
This won't work in 1.9: "RuntimeError: can't modify array during
iteration".
Best,
Andre
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
# arr.delete_at(arr.index(2))
# (Of course that's limited to #== comparisons. Maybe
# Array#index should
# take a block...)
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
From: Joel VanderWerf [mailto:vjoel@path.berkeley.edu]