From: Anton Bangratz Date: 2007-10-19T15:01:22+09:00 Subject: Re: array help --------------enig4B221558E003DF098B8FE353 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable JeremyWoertink@gmail.com wrote: > I have [1,2,3] and I want to return [1,2] is there already a method > that does this? >=20 > irb(main):001:0> [1,2,3] > =3D> [1, 2, 3] > irb(main):002:0> [1,2,3].pop > =3D> 3 > irb(main):003:0> [1,2,3].everything_but_the_one_thing_that_pop_returns >=20 Hello Jeremy, your problem is a mite unclear, I'll try to cover a few possible problems and their solutions ## # Returning parts irb(main):001:0> [1,2,3][0..1] # return the first two elements =3D> [1, 2] irb(main):004:0> [1,2,3].slice(0,2) # same as above, slice and [] are in the end the same method =3D> [1, 2] irb(main):005:0> [1,2,3][0..-2] # return everything but the last =3D> [1, 2] # And now, the very 'interesting' way: map each value to it's own # value, but to nil when it's '3' and remove the nil values from # the array irb(main):011:0> [1,2,3].collect() {|i| i unless i =3D=3D 3 }.compact =3D> [1, 2] ## # Manipulating in-place irb(main):015:0> a =3D [1,2,3] =3D> [1, 2, 3] irb(main):016:0> a.delete(3) # delete everything with the value '3' =3D> 3 irb(main):017:0> a =3D> [1, 2] irb(main):021:0> a =3D [1,2,3] =3D> [1, 2, 3] irb(main):022:0> a.delete_if {|i| i =3D=3D 3} # same as above =3D> [1, 2] irb(main):023:0> a =3D> [1, 2] # Delete the element at position '2', which incidentally is the last # one irb(main):028:0> a =3D [1,2,3] =3D> [1, 2, 3] irb(main):036:0> a.delete_at(2) # could also use (a.size-1) =3D> 3 irb(main):037:0> a =3D> [1, 2] # Delete the element at the last position irb(main):038:0> a =3D [1,2,3] =3D> [1, 2, 3] irb(main):039:0> a.delete_at(-1) =3D> 3 irb(main):040:0> a =3D> [1, 2] =2E.. so far on a little fun with arrays. Note that in-place manipulation actually works on the array itself, which might or might not be what you want. t. --=20 Anton Bangratz - Key ID 363474D1 - http://tony.twincode.net/ fortune(6): Q: What do they call the alphabet in Arkansas? A: The impossible dream. --------------enig4B221558E003DF098B8FE353 Content-Type: application/pgp-signature; name="signature.asc" Content-Description: OpenPGP digital signature Content-Disposition: attachment; filename="signature.asc" -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iQEVAwUBRxhILAgZMsE2NHTRAQK4QAf6AoybzouQusWC/kUm9B0kFtkrC7+0VZh8 b7YUr41dwaAaHIJeyjCl71owIcsuhVd1Gjs/d+tARPqh83TgQdadPcPkSaAmJhB5 QanOPeCvbdGc69m54f832KIVoVDa3alDTYfIUDVcFRzd/Viewb/KU4wbXMU83Mc1 bXFX5PebbZzURfjrhximLALdSWua1+AtKlwyf9cVM33eIizSsD6q24ob+d+GzcE/ KCa6HJFH+5m+SqiyaQjdwQjzT1h+sQ2Bl+OYLE4xuldFnuLFeUmbBALXIPFbjNPG p4ACPgC0tvoRi91avP6+8vJqu6X0pDX8U9ZO8ZlRyPwzIKLIiTDjzw== =/YDw -----END PGP SIGNATURE----- --------------enig4B221558E003DF098B8FE353--