2009-12-14 13 views
0

我有一個Ruby散列相匹配:填充紅寶石數組1與數組2字符串元素,當且僅當數組2元哈希值(不是鍵)

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

和陣列:

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

問題:如何我可以填充一個新的array1,這樣它只能拉入與VALS中的值完全匹配的array2中的任何值?

例如,我曾嘗試:

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錯誤。我肯定錯過了什麼。

回答

6

如果兩個集合都很大,那麼使用嵌套循環會非常緩慢。這是更好地把內容作爲集:

array1 = VALS.values & array2 
print array1 

輸出:

One 
+0

不知道&操作符作爲數組的集合交集。每天學習一些新東西:) +1 – 2009-12-14 05:44:00

+0

嗯......不需要'設置'的作品..永遠不會想到! 但如果我想獲得匹配第i個元素的數組的第i + 1個元素,怎麼樣? – Eric 2009-12-14 05:44:28

0

這裏有一個選項:

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

p array.select { |i| hash.has_value? i } 
# >> ["One"] 
+0

謝謝!我將如何選擇每場比賽的i + 1值? – Eric 2009-12-14 05:46:40

+0

我不會推薦'i'作爲代表數組成員的塊參數。我只會用它來表示一個索引號。 – 2011-10-14 02:09:09

0

得到它!

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