0

i want to save objects into an array. I have JSON objects and I want to save every object in an array to access every element alone. Can anybody help me?

toArray = JSON.parse(res.body)

categ = Array.new
i = 0

toArray.each do |object|
newMyObject = MyObject.new(object)
categ = Array.new(i, newMyObject)
i = i+1
end
2
  • thank you for your comment. how can i do that? i have to access every single element in the json later. Commented Apr 23, 2017 at 9:15
  • As a note, Ruby strongly encourages using lower-case only variables and method names, so to_array is to be expected here. Capital letters are reserved for ClassName or CONSTANT_NAME situations. Commented Apr 23, 2017 at 9:39

1 Answer 1

2

Try this one

array_from_json = JSON.parse(res.body)
objects_array = array_from_json.map { |item| MyObject.new(item) }

The issue in your code is that you are creating a new array every iteration.

Sign up to request clarification or add additional context in comments.

6 Comments

thank you. can you explain me, what the code does exactly?
Probably you don' know map method. That permit you to transform every element of an array and return a new array. In this case we are trasforming every element from the json to a MyObject object and the result is in the objects_array array object.
i get the error: "uninitialized constant MyObject (NameError) Did you mean? Object from test:51:in each' from test:51:in map' from test:51:in `<main>' " Can you help me please?
Well, I don't know. I saw that in your code. I though you had a MyObject class defined.
How can i do that? Can you help me please?
|

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.