4

I always end up writing the following code in order to obtain an array of values for a certain key:

hash.map{ |h| h['key'] || "default" }

Does anyone know a cleaner way of writing the same code?

Something like:

hash.map_keys(&:key, 'default')
dunyakirkali
  • 309
  • 6
  • 14
  • This makes no sense. Can you give us sample inputs and outputs? The line of code you've provided doesn't really accomplish anything sensible. – meager Aug 25 '15 at 15:22
  • I just realized myself that it makes no sense. What I mean is the following: I have an array of hashes: `[{email: 'a'}, {email: 'b'}]` from which I would like to obtain: `['a', 'b']` – dunyakirkali Aug 25 '15 at 15:22
  • 1
    Please don't clarify in comments, edit your question to make it clear. – meager Aug 25 '15 at 15:22
  • Why would you want to do `map_keys(&:key)`? `map_keys("key")` would make more sense. – sawa Aug 25 '15 at 15:28
  • 1
    @meagar I think you misinterpreted the question. Your answer seem to miss the point, and it is not a duplicate of the question you linked. The OP already knows how to do it (the OP's code is the same as the accepted answer to the question you linked). The OP is looking for a shorthand for that. – sawa Aug 25 '15 at 15:30
  • @sawa It's a difference between "how do I do X" and "what's the best way to do X". The answer is the same. – meager Aug 25 '15 at 15:31
  • 1
    @meagar The OP is particularly looking for a way to do it without explicitly writing a block. – sawa Aug 25 '15 at 15:32
  • @user3866597 `hash.map_keys(&:key, 'default')` is invalid. A block has come after the arguments. Therefore, it is impossible to do that. – sawa Aug 25 '15 at 15:34

2 Answers2

4

You can use hash.keys to get the hash keys.

To get the the values from an array of hashes for a key you can use fetch if you need to set a default.

Mats Rietdijk
  • 2,542
  • 3
  • 17
  • 25
1

If you want the values, you're after hash.values.

meager
  • 209,754
  • 38
  • 307
  • 315