I'd like to understand how the following code works:
def url
@url ||= {
"basename" => self.basename,
"output_ext" => self.output_ext,
}.inject("/:basename/") { |result, token|
result.gsub(/:#{token.first}/, token.last)
}.gsub(/\/\//, "/")
end
I know what it does; somehow it returns the url corresponding to a file located o a dir on a server. So it returns strings similar to this: /path/to/my/file.html
I understand that if @url
already has a value, it will be returned and the right ||=
will be discarded. I also understand that this begins creating a hash of two elements.
I also think I understand the last gsub; it replaces backslashes by slashes (to cope with windows servers, I guess).
What amazes me is the inject
part. I'm not able to understand it. I have used inject
before, but this one is too much for me. I don't see how this be done with an each
, since I don't understand what it does.
I modified the original function slightly for this question; the original comes from this jekyll file.
Cheers!