[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Array#find!

Trans

3/1/2008 12:45:00 AM

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.


5 Answers

7stud --

3/1/2008 1:15:00 AM

0

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

p arr

[1, 3, 2, 2, 2]

--
Posted via http://www.ruby-....

Christopher Swasey

3/1/2008 1:26:00 AM

0

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

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

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

Christopher

Joel VanderWerf

3/1/2008 1:30:00 AM

0

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

Andre Nathan

3/1/2008 2:11:00 AM

0

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


Peña, Botp

3/1/2008 2:21:00 AM

0

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