Home > front end >  How to print class attribute from array?
How to print class attribute from array?

Time:10-24

Say I have a class like so

class Date 
    attr_accessor :day, :month, :year
end

And I create 3 records for it, and add each to an array.

class Date 
    attr_accessor :day, :month, :year
end

date = Date.new()
date.day = 31
date.month = 12
date.year = 2019
array = []
array << date

date = Date.new()
date.day = 30
date.month = 2
date.year = 2014
array << date

date = Date.new()
date.day = 23
date.month = 1
date.year = 2012
array << date

If I wanted puts date.day (or every attribute) from the third record/third element of the array specifically, how would I access it (if I want to print it, or access it from a different function/procedure when specific user input is required)? Something like puts array[2] obviously doesn't work.

CodePudding user response:

array[2] would return the third element from the array. When you want to call day then you can write

puts array[2].day

If you want to print the day of all elements in the array you might want to do:

array.each do |element|
  puts element.day
end
  • Related