純粋なRubyの回答です。
コード
require 'date'
R1 =/
\s*-\s* # match a hypen optionally surrounded by whitespace
| # or
\s*to\s* # match 'to' optionally surrounded by whitespace
/x # free-spacing regex definition mode
R2 = /st|nd|rd|th # match one of the four pairs of letters
/x
def total_days(data)
data.lines.reduce(0) do |tot, str|
start_date, end_date = str.
chomp.
split(R1).
drop(1).
map { |s| Date.strptime(s.sub(R2, ''), '%d %b %Y') }
tot + (end_date - start_date).to_i
end
end
例
data =<<-_
Company 1 - 11th Feb 2008 to 23rd Feb 2010
Company 2 - 14 May 2010 to 17 Oct 2014
Company 3 - 22 Dec 2014 to 14 Jan 2017
_
total_days(data)
#=> 3114
説明
はDate::strptimeと(日付形式コードについて)DateTime#strftimeを参照してください。
手順は次のとおりです。
tot = 0
str = a.first
#=> "Company 1 - 11th Feb 2008 to 23rd Feb 2010\n"
:可変ブロック
str
の値になって、
a = data.lines
#=> ["Company 1 - 11th Feb 2008 to 23rd Feb 2010\n",
# "Company 2 - 14 May 2010 to 17 Oct 2014\n",
# "Company 3 - 22 Dec 2014 to 14 Jan 2017\n"]
変数tot
がreduce
の引数(0
)とa
の最初の要素に設定されているブロックが生成され、ブロックに渡されます
ブロック計算を実行しました
a = str.chomp
#=> "Company 1 - 11th Feb 2008 to 23rd Feb 2010"
b = a.split(R1)
#=> ["Company 1", "11th Feb 2008", "23rd Feb 2010"]
c = b.drop(1)
#=> ["11th Feb 2008", "23rd Feb 2010"]
d = c.map { |s| Date.strptime(s.sub(R2, ''), '%d %b %Y') }
#=> [#<Date: 2008-02-11 ((2454508j,0s,0n),+0s,2299161j)>,
# #<Date: 2010-02-23 ((2455251j,0s,0n),+0s,2299161j)>]
計算時にはd
、ブロックに渡さc
の最初の要素は
s = c.first
# => "11th Feb 2008"
であり、その文字列のブロックの計算は
g = s.sub(R2, '')
#=> "11 Feb 2008"
Date.strptime(g, '%d %b %Y')
#=> #<Date: 2008-02-11 ((2454508j,0s,0n),+0s,2299161j)>
継続、
start_date, end_date = d
#=> [#<Date: 2008-02-11 ((2454508j,0s,0n),+0s,2299161j)>,
# #<Date: 2010-02-23 ((2455251j,0s,0n),+0s,2299161j)>]
start_date
#=> #<Date: 2008-02-11 ((2454508j,0s,0n),+0s,2299161j)>
end_date
#=> #<Date: 2010-02-23 ((2455251j,0s,0n),+0s,2299161j)>
e = end_date - start_date
#=> (743/1) <rational>
f = e.to_i
#=> 743
tot + 743
#=> 743
f
日数は人です最初の仕事で働いた。最後の値は、ブロック変数tot
の新しい値です。これまでに処理されたすべてのジョブで処理された累積日数です。
ヒント:['Date.parse'](http://stackoverflow.com/questions/17563048/parse-a-date-in-rails)は、これらの日付形式をそのまま扱うことができます。 – tadman
あなたの質問はスタックオーバーフローには適していません。どこで検索しましたか、何を見つけましたか、なぜそれが役に立たなかったのですか?コードを書きましたか?そうでない場合、なぜですか?その場合、発生した特定の問題を示す最小限のコードはどこにありますか? "[ask]"と "[Stack Overflowユーザーにはどの程度の研究努力が必要ですか?](http://meta.stackoverflow.com/questions/261592)" –