Reputation: 2367
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?
Upvotes: 0
Views: 2704
Reputation: 1323
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.
Upvotes: 1
Reputation: 4218
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.
Upvotes: 0
Reputation: 370112
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.
Upvotes: 0
Reputation: 3472
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.
Upvotes: 4