LoginSignup
1
0

More than 3 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 さんね、便利な世の中やな。

おわり。

参考
- How do I create a Ruby date object from a string? - Stack Overflow
- class Date (Ruby 2.6.0)

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