I am not a ruby expert and this is giving me trouble. But how Would I go about creating an array of objects/classes in ruby? How would initialize it/declare it? Thanks in advance for the help.
This is my class, and I want to create an array of it:
class DVD
attr_accessor :title, :category, :runTime, :year, :price
def initialize()
@title = title
@category = category
@runTime = runTime
@year = year
@price = price
end
end
You can create an array by separating values by commas and enclosing your list with square brackets. In Ruby, arrays always keep their order unless you do something to change the order. They are zero-based, so the array index starts at 0.
In Ruby, there are several ways to retrieve the elements from the array. Ruby arrays provide a lot of different methods to access the array element. But the most used way is to use the index of an array.
Ruby | Array select() function Array#select() : select() is a Array class method which returns a new array containing all elements of array for which the given block returns a true value. Return: A new array containing all elements of array for which the given block returns a true value.
Ruby is duck typed (dynamic typing) And almost everything is an object, so you can just add any object to an array. For example:
[DVD.new, DVD.new]
will create an array with 2 DVDs in it.
a = []
a << DVD.new
will add the DVD to the array. Check the Ruby API for the full list of array functions.
Btw, if you want to keep a list of all the DVD instances in the DVD class you can do this with a class variable, and add it to that array when you create a new DVD object.
class DVD
@@array = Array.new
attr_accessor :title, :category, :runTime, :year, :price
def self.all_instances
@@array
end
def initialize()
@title = title
@category = category
@runTime = runTime
@year = year
@price = price
@@array << self
end
end
now if you do
DVD.new
you can get the list of all the DVDs you have created so far:
DVD.all_instances
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With