Discussion:
File.join compared with Pathname#join
Walter Lee Davis
2018-07-19 18:50:29 UTC
Permalink
This difference was surprising to me:

irb (2.4.4)
require ‘pathname’
Pathname.new(‘foo’).join(‘/bar’)
=> #<Pathname:/bar>
Pathname.new(‘foo’).join(‘bar’)
=> #<Pathname:foo/bar>

File.join(‘foo’, ‘/bar’)
=> “foo/bar”
File.join(‘foo’, ‘bar’)
=> “foo/bar”

Is there a reasonable explanation that I can’t think of for this behavior?

Walter

Unsubscribe: <mailto:ruby-talk-***@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/r
botp
2018-07-20 04:47:27 UTC
Permalink
​that is fine.
​
Post by Walter Lee Davis
irb (2.4.4)
require ‘pathname’
Pathname.new(‘foo’).join(‘/bar’)
=> #<Pathname:/bar>
​when you join an absolute path, it overrides (unjoins) all other existing
paths​ and makes it the new base path.
Post by Walter Lee Davis
Pathname.new("foo").join("/bar").join("baz")
=> #<Pathname:/bar/baz>

​> Pathname.new("foo").join("/bar").join("/ruby")
=> #<Pathname:/ruby>
​

Pathname.new(‘foo’).join(‘bar’)
Post by Walter Lee Davis
=> #<Pathname:foo/bar>
​ok

​
Post by Walter Lee Davis
File.join(‘foo’, ‘/bar’)
=> “foo/bar”
File.join(‘foo’, ‘bar’)
=> “foo/bar”
​File is very basic; just treats them as string w the file separator (yet
discards separator if you prepend one : ) Since file returns string
chaining fails thereafter,
Post by Walter Lee Davis
File.join("bar","foo").join("ruby")
NoMethodError: undefined method `join' for "bar/foo":String
Post by Walter Lee Davis
Is there a reasonable explanation that I can’t think of for this behavior?
​i think ruby doc is not so clear on this behaviour (havent check current
yet), but
this is common in other languages (eg python) or on other platforms​
Post by Walter Lee Davis
Walter
--
many thanks,
--botp
Continue reading on narkive:
Loading...