0

I have a custom class,

class Result

end

and i want to create an array of objects from it, but i cannot figure out how to do it? Because results = Array.new creates a new array, but i cannot find where to pass the class?

4 Answers 4

4

Presuming I understand the question correctly, the answer is: you don't. Ruby is dynamically typed, so the array is just an array and doesn't need to know that it's going to contain objects of class Result. You can put anything into the array.

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

1 Comment

To tag on, you can add objects of any class to your array. For example, arr1 = [] arr1.push(Result.new)
1

Are you looking for something like this,

class Result
end

result = Array.new(5) { Result.new }
#=> [#<Result>, #<Result>, #<Result>, #<Result>, #<Result>]

Obviously you can pass any number you want.

Comments

0

results = Array.new creates an empty array (as would results = [], which is more succinct). To create an array containing result objects, either create an empty array and add elements to it, or use an array literal like [element1, element2, ...].

For example results = [Result.new, Result.new, Result.new] would create an array containing three Result objects.

Comments

0

You should just be able to create as many Result objects as you need and append them to the array. The array can hold objects of any type.

result1 = Result.new
result2 = Result.new
result3 = Result.new

results = Array.new

results << result1
results << result2
results << result3

Your results array now has 3 Result objects in it.

Comments

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.