forked from adrianeyre/codewars
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileMaster.rb
More file actions
81 lines (65 loc) · 1.35 KB
/
FileMaster.rb
File metadata and controls
81 lines (65 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
=begin
This kata requires you to write an object that receives a file path and
does operations on it. NOTE FOR PYTHON USERS: You cannot use modules
os.path, glob, and re
Example of how the tests would work:
master = FileMaster.new('/Users/person1/Pictures/house.png')
master.extension
#--> png
master.filename
#--> house
master.dirpath
#--> /Users/person1/Pictures/
=end
# My solution
class FileMaster
def initialize(filepath)
@filepath = filepath
end
def extension
pos = @filepath.split("").index(".")
@filepath[pos+1..-1]
end
def filename
pos = @filepath.split("").rindex("/")
ext = @filepath.split("").index(".")
ext = @filepath.length - ext + 1
@filepath[pos+1..-ext]
end
def dirpath
pos = []
@filepath.split("").each_with_index {|x,i| pos << i if x == "/"}
@filepath[0..pos[-1]]
end
end
# Better Solution
class FileMaster
def initialize(filepath)
@fn = filepath
end
def extension
@fn.split('.')[-1]
end
def filename
ne = @fn.split('/')[-1]
ne.split('.')[0]
end
def dirpath
@fn[/\/.+\//]
end
end
# Another Solution
class FileMaster
def initialize(filepath)
@filepath = filepath
end
def extension
@filepath.scan(/.*\.(.*)/).join
end
def filename
@filepath.scan(/.*\/(.*)\..*/).join
end
def dirpath
@filepath.scan(/(.*\/).*/).join
end
end