2014-10-03 20 views
-3

我有一個Time對象,其中包含「05:37」之類的分鐘和秒。我想知道一種方法將其轉換爲下面的合成詞:「5分37秒」。在軌道中更改時間formate

+0

我不知道的Ruby-on-軌,但你應該使用正則表達式這一點。 – Jerodev 2014-10-03 12:09:47

+4

['DateTime#strftime'](http://apidock.com/ruby/DateTime/strftime) – 2014-10-03 12:14:00

回答

-2

沒關係了它:

[(total_response_time.to_i/counter_for_response_time.to_i)/60 % 60, (total_response_time.to_i/counter_for_response_time.to_i) % 60].map { |t| t.to_s.rjust(2,'0') }.join('m ') 

對於誰想把它轉換成這樣在未來的任何人。

+1

這與您的問題不同。什麼是total_response_time,counter_response_time? – tomsoft 2014-10-03 12:25:47

+0

和實現它的更簡潔的方法: (total_response_time.to_i/counter_for_response_time.to_i).tap {| t | s =「#{t/60} m#{t%60} s」} puts s – tomsoft 2014-10-03 12:30:36

+2

這看起來不是一個很好的方法來做任何事情**,它看起來很混亂和複雜。如果你有一個Time對象,那麼就像人們所說的那樣使用strftime。 – 2014-10-03 12:32:15

0

如果我們談論的時間目標,這很容易:

t=Time.now 
puts "#{t.min}m #{t.sec}s" 
=>15m 28s 

如果你有一個字符串

s="05:37" 
t=s.split(':').map{|i| i.to_i} 
puts "#{t.first}m #{t.last}s" 
=>5m 37s 

或更短

s.split(':').map{|i| i.to_i}.join("m ")+"s" 
0

雖然我同意意見建議strftime,你也可以只使用gsub

"05:37".gsub(/(\d+):(\d+)/, '\1m \2s') 
#=> "05m 37s" 

如果你不想要前導零,很容易擺脫。

0
[your_time_object].strftime('%Mm %Ss'). 

如需進一步詳細情況,請this