Ruby 从不使用';不包括分机

Ruby 从不使用';不包括分机,ruby,Ruby,例如: 如果运行此命令: require 'open-uri' local_path = 'app/assets/images/' image_url = 'https://www.gravatar.com/avatar/9784fd51f1db751e9806a0620f1c432b?s=32&d=identicon&r=PG' image_name = image_url.match( /[&=-_\w:]+$/i ).to_s; image_content =

例如:

如果运行此命令:

require 'open-uri'
local_path = 'app/assets/images/'

image_url = 'https://www.gravatar.com/avatar/9784fd51f1db751e9806a0620f1c432b?s=32&d=identicon&r=PG'
image_name = image_url.match( /[&=-_\w:]+$/i ).to_s;
image_content = open(image_url).read.to_s
# image_extension = File.extname(image_content) # doesn't work


puts image_content

File.open( local_path + image_name + '.jpg' , 'wb') do |out_file|
    out_file.write(image_content)
end
图像已成功保存,但我必须对“.jpg”进行硬编码以连接到文件名的末尾(请查看最后一行,但只有两行)


目的是将
'.jpg'
替换为
图像_扩展
,使其仍能正常工作。

,也许吧。您看过
内容类型
标题了吗?@swan和很好的建议!
require "open-uri"
require "mime/types"

image_url = 'https://www.gravatar.com/avatar/9784fd51f1db751e9806a0620f1c432b?s=32&d=identicon&r=PG'
image_download = open(image_url)
type = MIME::Types[image_download.content_type]
extension = type[0].extensions[0]
# => "png"