From: seebs@... (Peter Seebach) Date: 2007-05-04T02:00:11+09:00 Subject: Re: Array to Hash In message <20070503164957.06CAC41A5C@guild.seebs.net>, Peter Seebach writes: >In message <463a10df$0$27400$ba4acef3@news.orange.fr>, Josselin writes: >>is it possible to convert easily an Array like this one : >>[ nil, "b", nil, nil, nil , "f", "g", nil, nil, "j"] >>to an Hash like this one >>{ 1 => "b", 5 => "f", 6 => "g", 9 => "j" } >>where the key is the position of a value if not nil .. ? >Yes. I thought about this more. I'd like to explain WHY there's no code in the above: Because this is not just easy, but bloody obvious. What do you want to do? You want to, for each index in the array, record its value in a hash if it has a value. (Congrats! You've just reinvented sparse arrays! Please put your hand in the cookie jar to see whether there's a cookie.) So, what do you need? You need to do something for each index in the array. If ONLY the Array class provided an each_index method... Oh, but it does. So, given an index, can you imagine a way to write code to extract the member of an array at that index? You'd need some kind of operator to extract a member of an array. And a way to check whether a value is nil. All of these are not merely available, but easy. Even if you don't know that there's an each_index method, it's not hard to maintain a count and do 'count = count + 1; b[count] = x' or something similar. I guess this strikes me as a question that would have benefitted a lot from some explanation of why you weren't just looking at the Array documentation and trying a few things. -s