JVK
JVK

Reputation: 3912

ruby hash iteration without `each`

I have a ruby hash a as follows:

a = {
      "module" => 'students',
      "data" => [
        {
          "age" => 12,
          "uid" => 'sd3wrew'
        },
        {
          "age" => 10,
          "uid" => '43e43r'
        },
        {
          "age" => 10,
          "uid" => 'ft34f'
        }
      ]
    }

I want to collect all uid from above hash and get an array like:

b = ['sd3wrew', '43e43r', 'ft34f']

so, I have code to do this, which loop through it.

b = []
a['data'].each do |e|
  b << e['uid']
end

Is there anyway to achieve this result without looping each and much concise?

Upvotes: 1

Views: 299

Answers (2)

Endre Simo
Endre Simo

Reputation: 11551

This will print each key in a hash if key is equal with uid:

b = a["data"].each_key { |e| print e if e='uid' }

Upvotes: -2

Matt Ball
Matt Ball

Reputation: 359816

You're looking for the functional programming concept called "map."

b = a['data'].collect {|e| e['uid'] }
# or
b = a['data'].map {|e| e['uid'] }

http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-map

Upvotes: 8

Related Questions