5

I have a hash

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

and an array

a = [a, b]

Is it possible to use

h.select {|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) }
4
  • You should add your solution as an answer and accept it Commented Jul 8, 2011 at 9:19
  • You are asking for "all elements from the array that exist in the hash", but instead wanting "all elements from the hash whose keys exist in the array". The question was misleading and resulted with wrong answers. Commented Jul 8, 2011 at 12:30
  • I think is the same. all elements from the array that exist in the hash has the same meaning as all elements from the hash whose keys exist in the array! Commented Jul 8, 2011 at 12:34
  • 2
    It is not. In your solution you will get an array of [k, v] in R1.8, a hash in R1.9. This is definitely not the same as elements of an array. Commented Jul 8, 2011 at 13:42

4 Answers 4

2

You're going about it backwards. Try this:

a.select {|e| h.has_key? e }
Sign up to request clarification or add additional context in comments.

1 Comment

This is not working. The correct is h.select {|k,v| a.include?(k) }
1

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

Comments

1

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

Comments

0

One possible and the easiest answer is:

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

Comments

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.