Advertisement
Azure

birthdayclass

Mar 17th, 2012
320
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.59 KB | None | 0 0
  1. # @author Mark Seymour (mark.seymour.ns@gmail.com)
  2.  
  3. require 'date'
  4.  
  5. class Person
  6.   attr_accessor :first_name
  7.   attr_accessor :last_name
  8.   attr_accessor :birthday
  9.  
  10.   # @param [String] The person's first name
  11.   # @param [String] The person's last name
  12.   # @param [Date] The person's birthday
  13.   # @raise [TypeError] Raises TypeError if birthday is not a Date object.
  14.   def initialize first_name, last_name, birthday
  15.     @first_name = first_name.to_s.capitalize
  16.     @last_name = last_name.to_s.capitalize
  17.     # Only set birthday if it is a Date object. Otherwise, raise a TypeError
  18.     @birthday = (birthday.is_a?(Date) ? birthday : raise(TypeError, "Expected 'Date'"))
  19.   end
  20.  
  21.   # Determines whether the person's birthday is today or not.
  22.   # @todo Make it compatible with leap years
  23.   # @return [Boolean] True if the person's birthday is today, otherwise false.
  24.   def birthday?
  25.     today = Date.today
  26.     @birthday.mon == today.mon && @birthday.day == today.day ? true : false
  27.   end
  28.  
  29.   # Combines the first_name and last_name attributes into one.
  30.   # @param [Boolean] (false) Formats the name using the "Lastname, Firstname" convention.
  31.   # @return [String] The person's name
  32.   def fullname reversed = false
  33.     reversed ? "#{@last_name}, #{@first_name}" : "#{@first_name} #{@last_name}"
  34.   end
  35. end
  36.  
  37. # Note that I am using -1 for the year since I do not know Sean's birth year. ;)
  38. seanmorrow = Person.new("Sean", "Morrow", Date.new(-1,03,17))
  39. if seanmorrow.birthday?
  40.   puts "Happy Birthday, #{seanmorrow.fullname}!"
  41. else
  42.   puts "It's not #{seanmorrow.fullname}'s birthday... yet."
  43. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement