开发者

Use hash select for an array

I have a hash

h = {a=> 1, b=> 2, c=> 3}

and an array

a = [a, b]

Is it possible to use

h.se开发者_Go百科lect {|k,v| k == array_here?}

To select all elements from the array that exists in the hash?

I Found the Solution

h.select {|k,v| a.include?(k) }


You're going about it backwards. Try this:

a.select {|e| h.has_key? e }


You could achieve that with something like:

a.each do |arr_elem| 
  new_hash[arr_elem] = h[arr_elem] unless h[arr_elem].nil?
end


If you really want what you have asked (i. e. elements of an array which present as keys in a hash):

h = {:a => 1, :b => 2, :c => 3}
a = [:a, :b, :d]
a & h.keys


One possible and the easiest answer is:

h.select {|k,v| a.include?(k) }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜