From: "David A. Black" Date: 2005-12-03T01:11:37+09:00 Subject: Re: ruby one-liner needed Hi -- On Sat, 3 Dec 2005, David A. Black wrote: > Hi -- > > On Fri, 2 Dec 2005, David A. Black wrote: > >> Hi -- >> >> On Fri, 2 Dec 2005, 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 >> >> a = [1,2,3] >> b = [4,5,6,7,8] >> Hash[*a.zip(b[0,a.size]).flatten >> => {1=>4, 2=>5, 3=>6} > > Actually just use the shorter one first and zip won't fill it out with > nils: > > Hash[*a.zip(b).flatten] I hereby swear I will stop posting until I am being torn in no more than ten directions at the same time :-) In other words: I realize that you can't just switch them around at will. So you have to decide whether you're happy to have nils or if you want to truncate the hash based on available values. So adapt as needed :-) David P.S. One of the things I've been grappling with today is (the third day of) intermittent/non-existent Internet service -- and a mysterious reboot on my server. So I got and read this thread out of order. Sorry if I reinvented anyone's wheel :-) -- David A. Black dblack@wobblini.net "Ruby for Rails", forthcoming from Manning Publications, April 2006!