Ruby Programming/Reference/Objects/Time

From Wikibooks, open books for an open world
< Ruby Programming‎ | Reference‎ | Objects
Jump to: navigation, search
class Tuesdays
	attr_accessor :time, :place
 
	def initialize(time, place)
		@time = time
		@place = place
	end
end
 
feb12 = Tuesdays.new("8:00", "Rice U.")


As for the object, it is clever let me give you some advice though. Firstly, you don't ever want to store a date or time as a string. This is always a mistake. -- though for learning purposes it works out, as in your example. In real life, simply not so. Lastly, you created a class called Tuesdays without specifying what would make it different from a class called Wednesday; that is to say the purpose is nebulous: there is nothing special about Tuesdays to a computer. If you have to use comments to differentiate Tuesdays from Wednesdays you typically fail.

class Event
	def initialize( place, time=Time.new )
		@place = place
 
		case time.class.to_s
			when "Array"
				@time = Time.gm( *time )
			when "Time"
				@time = time
			else
				throw "invalid time type"
		end
	end
 
	attr_accessor :time, :place
 
end
 
## Event at 5:00PM 2-2-2009  CST
funStart = Event.new( "evan-hodgson day", [0,0,17,2,2,2009,2,nil,false,"CST"] )
 
## Event now, (see time=Time.new -- the default in constructor)
rightNow = Event.new( "NOW!" );
 
## You can compaire Event#time to any Time object!!
if Time.new > funStart.time
	puts "We're there"
else
	puts "Not yet"
end
 
## Because the constructor takes two forms of time, you can do
## Event.new( "Right now", Time.gm(stuff here) )