Populate ruby Array1 with Array2 String element if and only if Array2 element matches Hash value(not key)
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 <&开发者_StackOverflow社区lt; 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.
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
Here's an option:
hash = { :one => "One", :two => "Two" }
array = ["hello", "world", "One"]
p array.select { |i| hash.has_value? i }
# >> ["One"]
got it!
array.select do |i|
if VALS.has_value? i
result << array[array.index(i)+1]
end
end
精彩评论