Home > Mobile >  How to return the attribute value from an array in Ruby?
How to return the attribute value from an array in Ruby?

Time:11-23

I have a function which returns me a Array Objects, and I want to return the ID in an array (as I can have many objects), of which each object has one. Here's what I have tried.

 iban_obj.map{ |id| id },
 iban_obj.select(&:id)

Here is my iban_obj:

    [{"url"=>"xxxx.json",
  "id"=>360081391060,
  "title"=>"Test Macro",
  "active"=>true,
  "updated_at"=>"2021-11-22T13:15:06Z",
  "created_at"=>"2021-11-19T16:52:00Z",
  "position"=>10002,
  "description"=>"{{ iban }} {{ phone_number }} {{ email }}",
  "actions"=>
   [{"field"=>"comment_value_html",
     "value"=>
  "restriction"=>nil}]

Desired Result:

id_array = [360081391060]

CodePudding user response:

id_array = iban_obj.map { |obj| obj['id'] }

When you call #map each whole object will be passed in. From there you have to just select the proper key like you would from any hash.

CodePudding user response:

You can use dig method too..

banking_customer.map{ |customer| customer.dig('id') }
  • Related