From: "Shot (Piotr Szotkowski)" Date: 2009-12-12T05:18:12+09:00 Subject: Re: human-readable listing of array elements --OgqxwSJOaUobr8KG Content-Type: text/plain; charset=utf-8 Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Aldric Giacomoni: > This took me less than a minute to write, but I don't know if it's as > elegant as it could be. Are there more "Ruby-like ways(tm)" to write > this? > def stringify array > return array[0] if array.size =3D=3D 1 > string =3D "" > array.each_with_index do |element, index| > case index > when array.size - 1 # last item > string +=3D " and #{element}" > when 0 > string +=3D "#{element}" > else > string +=3D ", #{element}" > end > end > string > end Couldn=E2=80=99t resist: def stringify a a.size < 2 ? a.first.to_s : a[0..-2].join(', ') + " and #{a.last}" end >> stringify [] =3D> "" >> stringify ['Arthur'] =3D> "Arthur" >> stringify ['Arthur', 'Ford'] =3D> "Arthur and Ford" >> stringify ['Arthur', 'Ford', 'Trillian'] =3D> "Arthur, Ford and Trillian" >> stringify ['Arthur', 'Ford', 'Trillian', 'Marvin'] =3D> "Arthur, Ford, Trillian and Marvin" =E2=80=94 Shot --=20 a :message to you, Ruby --OgqxwSJOaUobr8KG Content-Type: application/pgp-signature; name="signature.asc" Content-Description: Digital signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAksiqQAACgkQi/mCfdEo8UopAQCghDsLAK7wQH1KG97qBXE9NzdZ 04gAnA/pFH4+Br0wAZTyEHWZZtd1oxBf =LTQ2 -----END PGP SIGNATURE----- --OgqxwSJOaUobr8KG--