cluv
cluv

Reputation: 620

How does a Ruby method handle an object for a parameter?

Say you have a Date class in java with this constructor:

public Date(int year, int month, int day)

and in this class you have a method that returns the number of days that this Date must be adjusted to make it equal to the given Date:

public int daysTo(Date other)

If you were to recreate this class in Ruby how would you handle this daysTo method?

Upvotes: 0

Views: 108

Answers (1)

danneu
danneu

Reputation: 9454

class MyDate
  attr_reader :days

  def initialize(days_since_epoch)
    @days = days_since_epoch
  end

  def days_to(other)
    other.days - days
  end
end

date1 = MyDate.new 100
date2 = MyDate.new 150
date1.days_to(date2) #=> 50

Upvotes: 2

Related Questions