views:

208

answers:

4

I am trying to populate an array with an intersection of an array and hash based on hash values:

array2 = ["hi","world","One"]
Vals = {:one => "One", :two => "Two"}
array2 = VALS.values & array2
print array2

Works fine for intersection of hash values and array2[ i ], but if I want to instead populate with array2[ i+1 ] element from array2, I am lost.

Also tried:

array2.select { |i| VALS.has_value? i ? array2[i+1] : nil }

But no luck.

Any ideas?

A: 
array = []
array2.each_with_index{|v,i| array << (VALS.has_value? i ?  array2[i+1] : nil)}
khelll
A: 

You may use

array2 = ["One", "1", "Two", "2", "Three", "3"]
vals = { :one => "One", :two => "Two" }
array2 = Hash[*array2].values_at(*vals.values)

this assumes that array2 is populated with an alternating sequence of keys and values (ie all your [i] are odd and all your [i+1] are even).

Adrian
A: 

It sounds to me like you're trying to treat your array as a series of either internal keys and values, or external keys into the inverse of vals. So the correct result from your example would be:

{"hi" => "World", "One" => :one}

Is that right? If so, here:

invertedvals = vals.invert
Hash[*array2.map {|x| [x,invertedvals[x]]}.flatten.compact]

If not, please clarify what result you're trying to produce...

glenn mcdonald
A: 

Here is what I ended up with as an answer to my own question:

array1.each do |i|
   puts "#"*5 + i + "#"*5 if !array2.include? i
  if array2.include? i
    result << i+":" << array2[array2.index(i)+1]
  end
end

Is there a speedier algorithm for this? Would like to use:

array1 & array2

Also used inject at one point, benchmark showed very little difference between any of them.

Eric