---
title: "Ruby文件操作"
author: "hnus"
date: "2015-04-15T14:36:00Z"
tags: []
slug: "ruby"
draft: false
lastmod: "2015-05-11T11:49:39Z"
id: 2210116
url: "https://hnus.iteye.com/blog/2210116"
---

获取不带目录的文件名（带有后缀）

```
File.basename( "foo/bar/jim-jam/whee.html" )       #=> "whee.html"
```

获取文件名（不带后缀）

```
File.basename( "foo/bar/jim-jam/whee.html", ".*" ) #=> "whee"
```

获取同一个目录下不同后缀的文件

```
filename  = File.basename(my_path,".*")
othername = File.join( File.dirname(my_path), "#{filename}.jpg" )
```

或者

```
othername = my_path.sub(/[^.]+\z/,"jpg")  # replace non-period characters at the end of the string with 'jpg'
```

参考：

http://ruby-doc.org/core-2.2.0/File.html

http://phrogz.net/filename-without-extension-ruby

http://stackoverflow.com/questions/23356777/ruby-get-filename-without-the-extensions

http://stackoverflow.com/questions/374326/get-filename-without-extension-from-file-path-in-ruby

```rb
irb(main):024:0> f = 'C:\foobar\blah.txt'.gsub("\\","/")
=> "C:/foobar/blah.txt"
irb(main):027:0> File.basename(f,File.extname(f))
=> "blah"
```