M
michael.dehaan
Recently at work I ran into a function that I felt like making more
Ruby-like (for fun), and having not delved into Ruby land much in the
last six months (Python was paying the bills), kind of at a loss to
whether there is a cleaner way to do this. Any pointers on style
here?
The task is this: Given a list of paths, remove any subdirectories or
files in the list if any parent directories of the file/subdirectory is
already in the list. Using "break" to get a value out of the inner
block felt a bit sloppy, but using "return" returns from the outermost
function, so it wasn't working well. I am mainly interested in
functional solutions.
Here's my shot:
def wash(files)
return files.reject do |name|
tokens = name.split("/")
rc = 2.upto(tokens.length()-1) do |idx|
break if files.include?(tokens[0,idx].join("/"))
end
rc.nil?
end
end
files = [
"/tmp/bar",
"/blah/zorg/2",
"/tmp/bar/baz",
"/foo",
"/blah/zorg/2/3",
"/blah/zorg",
"/zorg/blah",
"/blah/zorg/1",
]
expected = [
"/tmp/bar",
"/foo",
"/blah/zorg",
"/zorg/blah",
]
puts wash(files) == expected
Ruby-like (for fun), and having not delved into Ruby land much in the
last six months (Python was paying the bills), kind of at a loss to
whether there is a cleaner way to do this. Any pointers on style
here?
The task is this: Given a list of paths, remove any subdirectories or
files in the list if any parent directories of the file/subdirectory is
already in the list. Using "break" to get a value out of the inner
block felt a bit sloppy, but using "return" returns from the outermost
function, so it wasn't working well. I am mainly interested in
functional solutions.
Here's my shot:
def wash(files)
return files.reject do |name|
tokens = name.split("/")
rc = 2.upto(tokens.length()-1) do |idx|
break if files.include?(tokens[0,idx].join("/"))
end
rc.nil?
end
end
files = [
"/tmp/bar",
"/blah/zorg/2",
"/tmp/bar/baz",
"/foo",
"/blah/zorg/2/3",
"/blah/zorg",
"/zorg/blah",
"/blah/zorg/1",
]
expected = [
"/tmp/bar",
"/foo",
"/blah/zorg",
"/zorg/blah",
]
puts wash(files) == expected