Array#find!

T

Trans

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.
 
7

7stud --

Trans said:
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

p arr

[1, 3, 2, 2, 2]
 
C

Christopher Swasey

Trans said:
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

Why not just...
arr = [1, 2, 2, 2, 3]
arr.delete_at(arr.index(2))

arr => [1, 2, 2, 3]

Christopher
 
J

Joel VanderWerf

7stud said:
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...)
 
A

Andre Nathan

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
 
P

Peña, Botp

RnJvbTogSm9lbCBWYW5kZXJXZXJmIFttYWlsdG86dmpvZWxAcGF0aC5iZXJrZWxleS5lZHVdIA0K
IyBhcnIuZGVsZXRlX2F0KGFyci5pbmRleCgyKSkNCiMgKE9mIGNvdXJzZSB0aGF0J3MgbGltaXRl
ZCB0byAjPT0gY29tcGFyaXNvbnMuIE1heWJlIA0KIyBBcnJheSNpbmRleCBzaG91bGQgDQojIHRh
a2UgYSBibG9jay4uLikNCg0Kb2YgY291cnNlLCB3ZSBhZ3JlZSwgdGhhdCBpcyB3aHkgbWF0eiBw
dXQgaXQgaW4gMS45IDspDQoNCmlyYihtYWluKTowMTE6MD4gUlVCWV9WRVJTSU9ODQo9PiAiMS45
LjAiDQppcmIobWFpbik6MDEyOjA+IGENCj0+IFsidGhpcyIsICJpcyIsICJhIiwgInRlc3QiXQ0K
aXJiKG1haW4pOjAxMzowPiBhLmluZGV4e3xlfCBlPX4gL15pcy99DQo9PiAxDQppcmIobWFpbik6
MDE0OjA+IGENCj0+IFsidGhpcyIsICJpcyIsICJhIiwgInRlc3QiXQ0KaXJiKG1haW4pOjAxNTow
PiBhLmRlbGV0ZV9hdChhLmluZGV4e3xlfCBlPX4gL15pcy99KQ0KPT4gImlzIg0KaXJiKG1haW4p
OjAxNjowPiBhDQo9PiBbInRoaXMiLCAiYSIsICJ0ZXN0Il0NCg0KYW5kIDEuOSBpcyBmYXN0IDop
DQoNCmtpbmQgcmVnYXJkcyAtYm90cA0K
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,285
Messages
2,571,416
Members
48,107
Latest member
jigyasauniversity

Latest Threads

Top