Elegant way in Ruby to find first of possible matching hash keys

Lets say I have user input that can be either this:

input = { user_id: 5, ... }

or this:

input = { app_id: 5, ... }

And I want to return either :user_id or :app_id depending on which is provided. I can do this:

(input.keys & [:user_id, :app_id]).first

Is there a more elegant, more rubyish, idiomatic way of doing this?

Is this better or worse than above?:

input.slice(:user_id, :app_id).keys.first

(Answers don't need to be strictly from Ruby 2.2 stdlib, Rails methods welcome as well)

Answers


I would solve it the other way round using find and has_key?:

[:user_id, :app_id].find { |k| input.has_key?(k) }

Your solution is good enough. An alternative that I would prefer:

input = { app_id: 5, ... }

KEYS = [:app_id, :user_id, :foo_id]

input.find { |key, value| KEYS.include? key }

In that way, you keep the what you want separated from the how you want it. You could even make KEYS be assigned from a file so that you wouldn't even have to open the code to add or remove keys from the lookup. But that may be overengineering.

I would look for a better name for KEYS tough. Naming is hard.


Why not just:

input.key?(:user_id) ? :user_id : :app_id

? Am I missing something?


Need Your Help

Override Events in VB.NET

.net vb.net .net-2.0 shadow override

I would like to shadow/override an event in VB.NET.

Hint about a visual checked state in ListView

android listview drawerlayout

I'm quite new to Android and I don't understand how to achieve my goal. It's pretty simple, though.