简体   繁体   中英

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)

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM