--W/nzBZO5zC0uMSeA
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Fri, Sep 16, 2005 at 03:31:34AM +0900, itsme213 wrote:
> I have a hash table HASH containing strings, and want to generate a string
> for an equivalent Javascript variable JS from it e.g.
>=20
> HASH =3D {'a' =3D> 'A', 'b' =3D> 'B'}
>=20
> "var JS =3D { 'a' : 'A', 'b' : 'B' }"
>=20
> I thought inject was just the ticket:
>=20
> 'var JS =3D {' +
>   HASH.inject("") { |str, kv| str << "\n\t'#{kv[0]}' : #{kv[1]}, " } +
>   "};"
>=20
> But this puts a "," after the last item. Is there a simple alternative?

I think it's best solved in two steps, like this:

HASH.map { |k,v| "'#{k}' : '#{v}'"}.join(',')

Or you can do it with inject, but it's not as nice:

HASH.inject do |str,kv|
  if str.class =3D=3D Array
    str =3D "'#{str[0]}' : '#{str[1]}'"
  end
  str << ", '#{kv[0]}' : '#{kv[1]}'"
end

--W/nzBZO5zC0uMSeA
Content-Type: application/pgp-signature; name="signature.asc"
Content-Description: Digital signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)

iD8DBQFDKcSUnhUz11p9MSARAoZVAKCotMqtupfNKyplPK8/OYabNA0XMgCfYW6Y
TDn0TqnJHsAMegs0hCOYjhk=
=YjRh
-----END PGP SIGNATURE-----

--W/nzBZO5zC0uMSeA--

On Fri, Sep 16, 2005 at 03:31:34AM +0900, itsme213 wrote:
> I have a hash table HASH containing strings, and want to generate a string
> for an equivalent Javascript variable JS from it e.g.
>=20
> HASH =3D {'a' =3D> 'A', 'b' =3D> 'B'}
>=20
> "var JS =3D { 'a' : 'A', 'b' : 'B' }"
>=20
> I thought inject was just the ticket:
>=20
> 'var JS =3D {' +
>   HASH.inject("") { |str, kv| str << "\n\t'#{kv[0]}' : #{kv[1]}, " } +
>   "};"
>=20
> But this puts a "," after the last item. Is there a simple alternative?

I think it's best solved in two steps, like this:

HASH.map { |k,v| "'#{k}' : '#{v}'"}.join(',')

Or you can do it with inject, but it's not as nice:

HASH.inject do |str,kv|
  if str.class =3D=3D Array
    str =3D "'#{str[0]}' : '#{str[1]}'"
  end
  str << ", '#{kv[0]}' : '#{kv[1]}'"
end
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)

iD8DBQFDKcSUnhUz11p9MSARAoZVAKCotMqtupfNKyplPK8/OYabNA0XMgCfYW6Y
TDn0TqnJHsAMegs0hCOYjhk=
=YjRh
-----END PGP SIGNATURE-----