Bill Bisco Bill Bisco - 3 years ago 148
Ruby Question

Ruby: Return Values of Inputs to Class

My test code says the following:

d001 = SimpleDate.new(2016, 1, 4)
assert(d001.year == 2016)


When an input of of year is 2016 I want this test to properly get back 2016

My class code says the following

class SimpleDate
def initialize(year, month, day)
@year = year
@month = month
@day = day
end
end


What else do I have to put to be able to put
SimpleDate.new(2016,1,4).year == 2016
and not get an error from my class? I was hoping
@year
would do it.

Answer Source

Add an attr_reader for the year.

class SimpleDate
  attr_reader :year

  def initialize(year, month, day) 
    @year = year
    @month = month
    @day = day
  end
end

That is the same as

def year
  @year
end
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download