我们希望用缩略图版本优化图像,它存储在现有URL的时髦版本下:
原始图像:
https://image.s3-us-west-2.amazonaws.com/8/flower.jpg
缩略图:
https://image.s3-us-west-2.amazonaws.com/8/缩略图/medium_flower.jpg
我要从字符串的末尾查找最后一个'/'并用'/thumbnails/medium_'替换它在我的例子中,这总是安全的,但是我无法在Ruby on Rails中找出这种变异。

s = "https://image.s3-us-west-2.amazonaws.com/8/flower.jpg"
img_url = s.split('/')[-1] // should give 'flower.jpg'

问题是在最后一个'/'注入'thumbnails/medium_'之前获取所有内容有什么想法吗?

最佳答案

s = "https://image.s3-us-west-2.amazonaws.com/8/flower.jpg"
img_url = s.insert(s.rindex('/')+1, 'thumbnails/medium_')

# The above approach modifies the original string, if this is unsatisfactory, use:
img_url = s.dup.insert(s.rindex('/')+1, 'thumbnails/medium_')

10-07 16:19