1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Ruby] 文字列からDateクラスのインスタンスを生成する

Posted at

超シンプルなことなのに、なぜか僕は毎回忘れてしまう。

こうやって投稿することで、もう2度と忘れることはないだろう(期待)

やりたいこと

"1996-03-01"

みたいな文字列から、この日付の Date クラスのインスタンスを生成したい。

結論

parse メソッドを使うだけ

Date.parse("1996-03-01")
# => Fri, 01 Mar 1996

無駄な努力

ここから先は読む必要ないです。

これまで僕は、Date クラスでインスタンス生成できるの new しか知らんかった。

Date.new("1996-03-01")
# ArgumentError (comparison of String with 0 failed)

無理やりぶち込もうと思っても怒られる。

だから毎回こんなことやってた。

list = "1996-03-01".split('-').map(&:to_i)
Date.new(list[0], list[1], list[2])
# => Fri, 01 Mar 1996

parse さんね、便利な世の中やな。

おわり。

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?