From: Chad Perrin Date: 2011-04-02T08:06:55+09:00 Subject: Re: Simple array.each do |x| question --8P1HSweYDcXXzwPJ Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Sat, Apr 02, 2011 at 04:29:13AM +0900, Kyle X. wrote: > Thank you all for your responses. I have a second part question. I=20 > still cannot get the array.each do || correct, so I have been having to= =20 > use these long and unsophisticated while loops: >=20 > ------------------------------------- > n =3D 0 > elements =3D [] > while n !=3D reference1.length > x =3D=20 > REXML::XPath.match(doc,"//*[@id=3D'#{reference2[n]}']/Coordinates/IfcLeng= thMeasure").map=20 > {|element| element.text} > elements << x > n=3Dn+1 > end >=20 > n =3D 0 > result =3D [] > while n !=3D elements.length > a =3D 0 > while a !=3D elements[n].length > x =3D elements[n][a].to_f > result << x > a =3D a+1 > end > n=3Dn+1 > end > ------------------------------------ It occurs to me that you're just going through all the elements of an array within an array here, in order, such that if you have this array: [[0,1,2],[3,4,5],[6,7,8]] =2E . . you're just operating the elements as though the entire data structure was nothing but a flat array: [0,1,2,3,4,5,6,7,8] Keeping that in mind, you could use a basic elements.flatten.each block instead: result =3D [] elements.flatten.each {|n| result << n.to_f } You could use a map/collect block instead, which I think is clearer: result =3D elements.flatten.collect {|n| n.to_f } I find "collect" a more mnemonically helpful term for this operation given Ruby's block syntax, though "map" works well for me in Perl. In Ruby, the terms are interchangeable, so if you really want to type less you could use "map" instead of "collect" here. It occurs to me that the solution I gave you last time (assuming it works) could be combined with this one: result =3D reference2.each do |ref| REXML::XPath.match( doc, "//*[@id=3D'#{ref}']/Coordinates/IfcLengthMeasure" ).map {|element| element.text } end.flatten.map {|n| n.to_f } Feel free to swap out do . . . end with { . . . } or map with collect as needed, of course -- or to keep things separate if you think that's clearer. Ultimately, clarity of intent is probably the most important factor in deciding how to format your code. --=20 Chad Perrin [ original content licensed OWL: http://owl.apotheon.org ] --8P1HSweYDcXXzwPJ Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.14 (FreeBSD) iEYEARECAAYFAk2WV6gACgkQ9mn/Pj01uKWdrQCgnvn+D/baD3l2Ey6RPAiA4cm8 ra4AoIHFq6WldoOMVpIfpisenxQkfQjx =6vOr -----END PGP SIGNATURE----- --8P1HSweYDcXXzwPJ--