0

I have a Hash as follows:

{'a' => [title: 'ab', path: 'cd'], 'b' => [title: 'ef', path: 'gh']}

Now lets say I have one title and wish to get the key from it...

i.e. if I have 'ef' and want 'b'

This is what I'm currently doing, but it seems extremely clunky...

def get_hash_key(hash)
  hash.each do |k, h|
    return k if h[0][:title] == 'ef'
  end
end
h = {'a' => [title: 'ab', path: 'cd'], 'b' => [title: 'ef', path: 'gh']}
get_hash_key(h)

Is there another better way of doing this?

4
  • 2
    @sawa Sorry I'm confused, what do you mean that it isn't a valid ruby object - it works in irb Commented Sep 25, 2014 at 7:20
  • 1
    @sawa its basically a hash within an array within a hash Commented Sep 25, 2014 at 7:24
  • I see. You omitted the hash within an array. Commented Sep 25, 2014 at 7:39
  • Surprise, surprise! ` [title: 'ab', path: 'cd'] #=> [{:title=>"ab", :path=>"cd"}]`, at least in Ruby 2.1. Commented Sep 25, 2014 at 7:43

2 Answers 2

2
h = {'a' => [title: 'ab', path: 'cd'], 'b' => [title: 'ef', path: 'gh']}
h.select { |_,v| v[0][:title] == 'ef' }.keys
# => [
#   [0] "b"
# ]
Sign up to request clarification or add additional context in comments.

Comments

1
h = {'a' => [title: 'ab', path: 'cd'], 'b' => [title: 'ef', path: 'gh']}
  #=> {"a"=>[{:title=>"ab", :path=>"cd"}], "b"=>[{:title=>"ef", :path=>"gh"}]}

h.each_with_object({}) { |(k,v),g| g[v.first[:title]] = k }['ef'] 
  #=> "b"

or

h.each_with_object({}) { |(k,v),g| g[k] = v.first[:title] }.invert['ef']
  #=> "b"

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.