注入字符串的最简洁方法

时间:2015-08-05 22:20:53

标签: ruby string url

我们希望使用缩略图版本优化图片,这些版本存储在现有网址的时髦版本中:

我将从字符串末尾查看最后一个'/'并将其替换为'/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_'之前获取所有内容。有什么想法吗?

5 个答案:

答案 0 :(得分:4)

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_')

答案 1 :(得分:3)

s = "https://image.s3-us-west-2.amazonaws.com/8/flower.jpg"
img_url = "#{File.dirname(s)}/thumbnails/medium_#{File.basename(s)}"
# => "https://image.s3-us-west-2.amazonaws.com/8/thumbnails/medium_flower.jpg"

答案 2 :(得分:2)

我可能会使用URIPathname来处理网址和文件路径:

require 'uri'
require 'pathname'

url = "https://image.s3-us-west-2.amazonaws.com/8/flower.jpg"

uri  = URI.new(url)
path = Pathname.new(uri.path)
uri.path = "#{path.dirname}/thumbnails/medium_#{path.basename}"

uri.to_s
#=> "https://image.s3-us-west-2.amazonaws.com/8/thumbnails/medium_flower.jpg"

答案 3 :(得分:1)

s = "https://image.s3-us-west-2.amazonaws.com/8/flower.jpg"
s.sub /([^\/]+)$/, 'thumbnails/medium_\1'

s.sub的第二个参数应使用单引号引用,或者您必须转义\1部分中的反斜杠。

更新

s.sub /([^\/]+?)(?=$|\?|#)$/, 'thumbnails/medium_\1'

如果查询字符串或片段或两者都在路径后面,其中包含斜杠。

答案 4 :(得分:0)

你需要#[Range]方法:

# a little performance optimization - no need to split split string twice
parts = s.split('/')
img_url = parts[0..-2].join('/') + "/thumbnails/medium_" + parts[-1]

旁注。如果您使用一些Rails插件来处理图像(CarrierWavePaperclip),则应使用内置机制进行URL插值。