0

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.

3
  • 1
    The name Date is a really bad choice as its already a part of the Ruby standard library. Commented Oct 23, 2021 at 23:27
  • Ah ok. Is there a way to see beforehand what's part of Ruby's standard library/a way to check for it? Commented Oct 25, 2021 at 8:52
  • well that's a bit tricky - Date isn't actually defined until you require it. There are several list of reserved words in Ruby but I guess the only real way to check for name collision is to search the docs. Commented Oct 25, 2021 at 10:44

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

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.