From: William James Date: 2005-09-16T04:01:34+09:00 Subject: Re: Appropriate use of "inject()" ? 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. > > HASH = {'a' => 'A', 'b' => 'B'} > > "var JS = { 'a' : 'A', 'b' : 'B' }" > > I thought inject was just the ticket: > > 'var JS = {' + > HASH.inject("") { |str, kv| str << "\n\t'#{kv[0]}' : #{kv[1]}, " } + > "};" > > But this puts a "," after the last item. Is there a simple alternative? > > Thanks. puts "var JS = {\n\t" + HASH.map{|k,v| "'#{k}' : #{v}" }.join(",\n\t") + " };"