0

我有一个红宝石哈希:

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

和一个数组:

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

问题:如何填充一个新的 array1 以便它只提取 array2 中与 VALS 中的值完全匹配的任何值?

例如,我尝试过:

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

连同其他东西,没有工作。小白。

谢谢


杰出的!但是当我尝试时:

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

我遇到了无法转换 fixnum 错误。我肯定错过了什么。

4

3 回答 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
于 2009-12-14T05:36:34.453 回答
0

Here's an option:

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

p array.select { |i| hash.has_value? i }
# >> ["One"]
于 2009-12-14T05:38:13.200 回答
0

知道了!

array.select do |i|
  if VALS.has_value? i
    result << array[array.index(i)+1]
  end
end
于 2009-12-14T07:09:47.433 回答