2014-10-03 56 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