0

I have a ruby hash:

VALS = { :one => "One", :two => "Two" }

and an Array:

array2 = ["hello", "world", "One"]

Question: How can I populate a new array1 so that it only pulls in any values in array2 that match exactly the values in VALS?

For example, I have tried:

array2.each_with_index do |e,i| 
array1 << e if VALS[i] ~= e
end

Along with other thing, and none work. Noob.

Thanks


brilliant! but whent I tried:

p array.select { |i| hash.has_value? i ? array[i+1] : "foo"}

I got an can't convert fixnum error. I must be missing something.

3 Answers 3

6

Using nested loops would be very slow if both collections are large. It's better to treat the contents as sets:

array1 = VALS.values & array2
print array1

Output:

One
2
  • Did not know that & operator operates as set intersection for arrays. Learn something new every day :) +1 Commented Dec 14, 2009 at 5:44
  • hmmm... works without require 'set' too.. never would have thought! but how about if I want to get the i + 1th element of the array that matched for the ith element? Commented Dec 14, 2009 at 5:44
0

Here's an option:

hash = { :one => "One", :two => "Two" }
array = ["hello", "world", "One"]

p array.select { |i| hash.has_value? i }
# >> ["One"]
1
  • I wouldn't recommend i being used as the block parameter representing a member of an array. I'd only use it to represent an index number. Commented Oct 14, 2011 at 2:09
0

got it!

array.select do |i|
  if VALS.has_value? i
    result << array[array.index(i)+1]
  end
end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.