pathinfo
-
The
pathinfofunction in PHP returns an associative array with information about a file path. The array should contain the keysdirname,basename,extension, andfilename.PHP
$pathinfo = pathinfo('/path/to/foo.bar'); var_export($pathinfo); //=> array ( // 'dirname' => '/path/to', // 'basename' => 'foo.bar', // 'extension' => 'bar', // 'filename' => 'foo', // )
Ruby does not have an equivalent method to
pathinfo. However, theFileclass contains individual methods that can return the same information. It is preferable to use these individual methods:File.dirname,File.basename, andFile.extname.If a
pathinfomethod is convenient, one approach would be to take advantage of Ruby’s open classes to monkeypath a new method onto theFileclass:Ruby
class File def self.pathinfo(path) { :basename => basename(path), :dirname => dirname(path), :extension => extname(path), :filename => basename(path, extname(path)) } end end
You could then call
File.pathinfo:Ruby
pathinfo = File.pathinfo('/path/to/foo.bar') p pathinfo #=> { :basename => "foo.bar", # :dirname => "/path/to/foo.bar", # :extension => ".bar" # :filename => "foo" }
The snippet above is roughly equivalent but has a minor difference from the PHP version. The
File.extnamemethod returns the leading period (.bar) but theextensionelement returned by PHP’spathinfodoes not.see also
Looking for Rails or PHP web application development, integration, and training?
Rails for PHP is brought to you by Maintainable Software. Get custom web applications and personalized training from the authors of the book and website.

