Forum: Ruby Beginner array manipulation questions

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
2cf408af3f08d3575c9cd7697158a8f1?d=identicon&s=25 Jamal Mazrui (Guest)
on 2006-04-10 16:27
(Received via mailing list)
Suppose the variable path is an array of fully qualified path and file
names (e.g., in Windows, an item might be "c:\folder\file.txt").  What
would be an efficient way of creating another array that contained only
the file extensions (one or more characters following the last .
character, if any)?  I know I could use a while loop and a counter, but
figure there is a better way in Ruby.

Alternatively, how could I change the array so that it was two
dimensional where each "row" had two "columns" consisting of the full
name and the extension only?

Jamal
4299e35bacef054df40583da2d51edea?d=identicon&s=25 James Gray (bbazzarrakk)
on 2006-04-10 16:39
(Received via mailing list)
On Apr 10, 2006, at 9:26 AM, Jamal Mazrui wrote:

> Suppose the variable path is an array of fully qualified path and file
> names (e.g., in Windows, an item might be "c:\folder\file.txt").  What
> would be an efficient way of creating another array that contained
> only
> the file extensions (one or more characters following the last .
> character, if any)?  I know I could use a while loop and a counter,
> but
> figure there is a better way in Ruby.

 >> files = %w{c:\folder\file1.txt c:\folder\file2.exe c:\folder
\file3.pdf} => ["c:\\folder\\file1.txt", "c:\\folder\\file2.exe", "c:\
\folder\\file3.pdf"]
 >> files.map { |f| File.extname(f) }
=> [".txt", ".exe", ".pdf"]

> Alternatively, how could I change the array so that it was two
> dimensional where each "row" had two "columns" consisting of the full
> name and the extension only?

 >> files.map { |f| e = File.extname(f); [f[0..(-1 - e.length)], e] }
=> [["c:\\folder\\file1", ".txt"], ["c:\\folder\\file2", ".exe"], ["c:
\\folder\\file3", ".pdf"]]

Hope that helps.

James Edward Gray II
This topic is locked and can not be replied to.