1

I have an Array whose content is as follow:

[
     [0] {
                   "name" => “Mark”,
                     "id" => “01”,
            "description" => “User”,
     },
     [1] {
                   "name" => “John”,
                     "id" => “02”,
            "description" => “Developer”,
     }
] 

Note: right now each item of the Array is a Hash (not a string). That is to say that if I do puts myarray[0].class I get hash in return.

I would like to be able to create an object that I can reference as object[i].field.

For example I'd like to be able to get "Mark" by calling object[0].name or get "Developer" by calling object[1].description.

Is this possible? I have tried to leverage the .to_json method against my array but it doesn't quite give me what I need.

Thanks.

1 Answer 1

3

You can do use Struct to meet your need.

array = [
  {
    "name" => "Mark",
    "id" => "01",
    "description" => "User",
  },
  {
    "name" => "John",
    "id" => "02",
    "description" => "Developer",
  }
] 

Customer = Struct.new(:name, :id, :description)
array_of_customers = array.map { |hash| Customer.new(*hash.values) }
array_of_customers[1].name # => "John"
array_of_customers[1].description # => "Developer"
Sign up to request clarification or add additional context in comments.

1 Comment

OMG that's exactly what I wanted to do. It works perfectly. Thanks so much Arup!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.