From: Ross Bamford Date: 2005-12-02T19:22:32+09:00 Subject: Re: ruby one-liner needed On Fri, 02 Dec 2005 09:00:30 -0000, Kev Jackson wrote: > Here's one taht I know is possible (I'm sure I've seen it somewhere > before) > > I have 2 arrays and I'd like to change them into a Hash > stuff = ["1", "2", "3"] > Item.column_names.each { |column_name| new_item[column_name] = stuff[?] } > > The problem is how to index within the block to move along the stuff > array, and how to deal with the fact that most of the time the stuff > array is shorter than the column_names array > > I'm sure using collect, map of something else ruby-ish that this is more > than possible, but I can't find a solution right now > > Kev > > Well, theres lots of ways, but one is to inject the Hash as someone here showed me yesterday: items.column_names.inject({}) { |hash, column_name| hash[column_name] = row.shift ; hash } (I wanted to eliminate the '; hash' at the end of the closure but couldn't find a way yet...) However, I personally prefer Simon's solution, which can be a real one-liner too :) Hash[*items.column_names.zip(row).flatten] -- Ross Bamford - rosco@roscopeco.remove.co.uk "\e[1;31mL"