1

我搜索了我的问题并得到了很多解决方案,但不幸的是没有一个能满足我的需求。

我的问题是,我有两个或多个字符串,我想将这些字符串转换为时间,然后添加它们:

time1 = "10min 43s"
time2 = "32min 30s"

输出将是:43min 13s

我尝试的解决方案是:

time1 = "10min 43s" 
d1=DateTime.strptime(time1, '%M ') 
# Sat, 02 Nov 2013 00:10:00 +0000 
time2 = "32min 30s" 
d2=DateTime.strptime(time2, '%M ') 
# Sat, 02 Nov 2013 00:32:00 +0000 

那我就没法进步了。

4

4 回答 4

2

有很多方法可以做到这一点。这是另一个:

time1 = "10min 43s"
time2 = "32min 30s"

def get_mins_and_secs(time_str)
  time_str.scan(/\d+/).map(&:to_i)
    #=> [10, 43] for time_str = time1, [32, 30] for time_str = time2 
end

min, sec   = get_mins_and_secs(time1)  
min2, sec2 = get_mins_and_secs(time2)  
min += min2
sec += sec2

if sec > 59
  min += 1
  sec -= 60
end

puts "#{min}min #{sec}sec"

让我们考虑一下这里发生了什么。首先,您需要从时间字符串中提取分钟和秒。我做了一个方法来做到这一点:

def get_mins_and_secs(time_str)
  time_str.scan(/\d+/).map(&:to_i)
    #=> [10, 43] for time_str = time1, [32, 30] for time_str = time2 
end

对于time_str = "10min 43s",我们应用该String@scan方法将两个数字提取为字符串:

"10min 43s".scan(/\d+/) # => ["10", "43"]

Array#map然后用于将这两个字符串转换为整数

["10", "43"].map {|e| e.to_i} # => [10, 43]

这可以更简洁地写成

["10", "43"].map(&:to_i} # => [10, 43]

通过链接mapscan我们获得

"10min 43s".scan(/\d+/).map(&:to_i} # => [10, 43]

数组[10, 43]由变量min和接收(解构)返回和接收sec

min, sec = get_mins_and_secs(time_str)

其余的很简单。

于 2013-11-01T19:36:16.103 回答
1

假设格式保持不变,这是一个简单的解决方案:

time1 = "10min 43s"
time2 = "32min 30s"
strings = [time1, time2]

total_time = strings.inject(0) do |sum, entry|
  minutes, seconds = entry.split(' ')
  minutes = minutes.gsub("min", "").to_i.send(:minutes)
  seconds = seconds.gsub("s", "").to_i.send(:seconds)
  sum + minutes + seconds
end
puts "#{total_time/60}min #{total_time%60}s"
于 2013-11-01T18:57:47.350 回答
1

像下面这样的东西应该可以解决问题:

# split the string on all the integers in the string
def to_seconds(time_string)
  min, sec = time_string.gsub(/\d+/).map(&:to_i)

  min.minutes + sec.seconds
end

# Divide the seconds with 60 to get minutes and format the output.
def to_time_str(seconds)
  minutes = seconds / 60
  seconds = seconds % 60

 format("%02dmin %02dsec", minutes, seconds)
end

time_in_seconds1 = to_seconds("10min 43s")
time_in_seconds2 = to_seconds("32min 30s")

to_time_str(time_in_seconds1 + time_in_seconds2)
于 2013-11-01T19:05:12.987 回答
0

我的解决方案采用任意数量的时间字符串并以相同的格式返回总和:

def add_times(*times)
  digits = /\d+/
  total_time = times.inject(0){|sum, entry|
    m, s = entry.scan(digits).map(&:to_i)
    sum + m*60 + s
  }.divmod(60)
  times.first.gsub(digits){total_time.shift}
end

p add_times("10min 43s", "32min 55s", "1min 2s") #=> "44min, 40s"
p add_times("10:43", "32:55") #=> "38:43"
于 2013-11-04T14:05:43.760 回答