跳至内容

Ruby 编程/参考/对象/时间

来自维基百科,一个面向开放世界的开放书籍
class Tuesdays
	attr_accessor :time, :place

	def initialize(time, place)
		@time = time
		@place = place
	end
end

feb12 = Tuesdays.new("8:00", "Rice U.")


至于对象,它很聪明,让我给你提一些建议。首先,你永远不想把日期或时间存储为字符串。这是一个错误。-- 不过出于学习目的可以这样做,就像你的示例中那样。但实际中并不可行。最后,你创建了一个名为 Tuesdays 的类,但没有指定它与名为 Wednesday 的类有何不同;也就是说目的很模糊:对计算机而言,星期二没有特别之处。如果你必须使用注释来区分类星期二与星期三,那你通常会失败。

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) )
华夏公益教科书