File.basename

File.open(‘myfile’) do |f|
puts f.basename;
end

myfile exists on the filesystem but this code blows up with

undefined method `basename’

could someone explain why (given the docs
http://ruby-doc.org/core/classes/File.html
advertise the basename method)

[ruby 1.8.7 (2010-01-10 patchlevel 249) [i486-linux]]

Thanks!

You do have FileUtils installed and required, yes?

require ‘ftools’

On 2010-07-20 10:08:40 -0400, James O’Brien said:

On Tue, Jul 20, 2010 at 11:08:40PM +0900, James O’Brien wrote:

advertise the basename method)
It’s a class method, not an instance method.

File.open(‘myfile’) do |f|
puts File.basename(f)
end

On Tue, Jul 20, 2010 at 5:08 PM, James O’Brien [email protected] wrote:

advertise the basename method)

Because it’s a class method, not an instance method. That is, you should
use
it as follows:

File.basename(“foo.bar”)

HTH,
Yaser

On Jul 20, 2010, at 10:08 AM, James O’Brien wrote:

advertise the basename method)

[ruby 1.8.7 (2010-01-10 patchlevel 249) [i486-linux]]

Thanks!

You’re looking at the docs for the class method File.basename, but
you’re calling basename on an instance of File referenced by f

puts File.basename(‘myfile’)

or better:

puts File.basename(’/some/long/path/to/myfile’)

-Rob

Rob B.
[email protected] http://AgileConsultingLLC.com/
[email protected] http://GaslightSoftware.com/

Yep yep silly me… THANKS everyone!

On Tue, Jul 20, 2010 at 3:52 PM, Rob B.

On Jul 20, 2010, at 8:07 , James O’Brien wrote:

Yep yep silly me… THANKS everyone!

And THAT is why I personally quit using File a long time ago. I
encourage you to take a close look at Pathname, which I found put the
various methods where I thought they should have been in the first
place.

require ‘pathname’
myFile = Pathname.new("/some/path/to/file.ext")
myFile.basename
=> “file.ext”

.delete, .dirname, .atime, .executable?, .exists?, .extname, and on and
on are properties of specific files, so having the methods on the
instance, instead of the class, just makes all kinds of sense to me.

Pathname only has three class methods, including new. Vastly more
intuitive to me.

On Jul 20, 2010, at 10:52 AM, Rob B. wrote:

could someone explain why (given the docs

puts File.basename(‘myfile’)

or better:

puts File.basename(’/some/long/path/to/myfile’)

Actually, a better example (and likely closer to what you expected):

puts File.basename(f.path)

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs