Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Array of Objects/Classes

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
like image 257
Chris Cruz Avatar asked Jan 26 '13 01:01

Chris Cruz


People also ask

How do you create an array of objects from a class in Ruby?

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.

How do you access an array of objects in Ruby?

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.

What does .select do in Ruby?

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.


1 Answers

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
like image 72
rik.vanmechelen Avatar answered Sep 28 '22 12:09

rik.vanmechelen