65

I have a data structure in the following format:

data_hash = [
    { price: 1, count: 3 },
    { price: 2, count: 3 },
    { price: 3, count: 3 }
  ]

Is there an efficient way to get the values of :price as an array like [1,2,3]?

Breno
  • 4,670
  • 1
  • 19
  • 24
Kert
  • 1,359
  • 3
  • 13
  • 14
  • 1
    The example you give is not valid ruby syntax. (Without a valid example we can't help you). Also, it would helpful if you show us what you've already tried. – tessi Sep 19 '13 at 16:15
  • 1
    We need to see your attempt at solving this problem. Without your code it looks like you're just asking someone to write code for you, which is a great way to get your question closed. Otherwise, we can simply say, "Yes, there is an efficient way to get the values" and leave it to you to figure it out. Which would you prefer? – the Tin Man Sep 19 '13 at 16:22
  • Probably the question should swap `{ }` and `[ ]` brackets (making it an array of hashes). I just tried for 5 mins to find an existing question (I am really convinced this is a duplicate), but I think SO has buried the answers under more complex examples. – Neil Slater Sep 20 '13 at 09:39
  • 7
    Use data_hash.pluck(:price) now, for the love of god – Rambatino Apr 24 '17 at 19:01
  • 1
    @Rambatino pluck is a rails method. This is a general ruby question. – Parker Kemp Sep 25 '20 at 19:14
  • @ParkerKemp old me was naïve, you are correct, there is no rails reference in here and that functionality does come from rails – Rambatino Sep 26 '20 at 12:06

1 Answers1

121

First, if you are using ruby < 1.9:

array = [
    {:price => 1, :count => 3},
    {:price => 2, :count => 3},
    {:price => 3, :count => 3}
]

Then to get what you need:

array.map{|x| x[:price]}
Breno
  • 4,670
  • 1
  • 19
  • 24
Zabba
  • 60,240
  • 44
  • 170
  • 200
  • 3
    The updated syntax for the "hash" is correct, but at that point `data_hash` is a misnomer. The OP should use `data_hashes` or `data_array`, either of which would be better. – the Tin Man Sep 19 '13 at 16:27
  • Oops, you are right. Corrected. – Zabba Sep 19 '13 at 16:28