Skip to content

Instantly share code, notes, and snippets.

@mnbi
Created October 6, 2020 03:13
Show Gist options
  • Save mnbi/e51a62ddb6d92cc6968afe70f6508df6 to your computer and use it in GitHub Desktop.
Save mnbi/e51a62ddb6d92cc6968afe70f6508df6 to your computer and use it in GitHub Desktop.
predicate whether a file exists in the search path
#
# Which implementation do you prefer?
#
# 1.
def exist_in_search_path_1?(file, paths)
paths.split(":").each { |dir|
return true if FileTest.exist?(File.expand_path(file, dir))
}
false
end
# 2.
def exist_in_search_path_2?(file, paths)
paths.split(":").reduce(false) { |r, dir|
r |= FileTest.exist?(File.expand_path(file, dir))
}
end
# 3.
def exist_in_search_path_3?(file, paths)
result = paths.split(":").map { |d| File.expand_path(file, d) }.find { |p|
FileTest.exist?(p)
}
!result.nil?
end
[:exist_in_search_path_1?, :exist_in_search_path_2?, :exist_in_search_path_3?].each { |m|
puts send(m, "cat", ENV["PATH"])
puts send(m, "catwoman", ENV["PATH"])
puts send(m, "bat", ENV["PATH"])
puts send(m, "batman", ENV["PATH"])
}
# I like 2. However, it is wasteful.
# 1 is the most efficient way, I think.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment