Skip to content

Instantly share code, notes, and snippets.

@eiel
Created February 7, 2013 04:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eiel/4728435 to your computer and use it in GitHub Desktop.
Save eiel/4728435 to your computer and use it in GitHub Desktop.
ブログで使うサンプルコード
require 'active_support/all'
datetime = DateTime.new 2013, 2, 7
date = Date.new 2013, 2, 7
time = Time.new 2013, 2, 7
datetime # => Thu, 07 Feb 2013 00:00:00 +0000
date # => Thu, 07 Feb 2013
time # => 2013-02-07 00:00:00 +0900
# レシーバによって動作が変わる (1)
# 1日先に
datetime + 1 # => Fri, 08 Feb 2013 00:00:00 +0000
# 1日先に
date + 1 # => Fri, 08 Feb 2013
# 1秒先に
time + 1 # => 2013-02-07 00:00:01 +0900
# これを防ぐには和をとるものを明示する (2)
datetime + 1.days # => Fri, 08 Feb 2013 00:00:00 +0000
date + 1.days # => Fri, 08 Feb 2013
time + 1.days # => 2013-02-08 00:00:00 +0900
# 秒の場合 (3)
datetime + 1.second # => Thu, 07 Feb 2013 00:00:01 +0000
date + 1.second # => 2013-02-07 00:00:01 +0900
time + 1.second # => 2013-02-07 00:00:01 +0900
# Class は どれも Fixnum なのです
1 # => 1
1.class # => Fixnum
1.days # => 1 day
1.days.class # => Fixnum
1.second # => 1 second
1.second.class # => Fixnum
# (1) の場合のみレシーバによって動作が変化。動作的には自然
# (2), (3) の場合は 引数に応じた動作に。 Dateは演算の結果、型が変化する。
# 使う分には自然で面白い
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment