Dir.glob("*.txt") {|f| p f} prints filenames.
Dir.glob("*.txt").sort {|f| p f} fails with an ArgumentError.
Dir.glob("*.txt").sort.each {|f| p f} prints filenames in alphabetical order.
Why does the second one fail? Better yet, why does the first one work, with or without the .each?
Dir.globandDir.glob.sortare both Arrays.Dir.glob.methods == Dir.glob.sort.methods.
(Inspired by Alphabetize results of Dir.glob. Not a duplicate of Dir.glob with sort issue because the "third one" already answers that one's question.)
The other answer is correct, but I think there is a deeper explanation. When you have a block after a method call, like
Dir.glob("*.txt") {|f| p f}, the block is an (optional) argument to the method. In the definition ofDir.glob, there is ayieldstatement that runs the block.When you chain the methods, like in
Dir.glob("*.txt").sort {|f| p f}, the block becomes an argument to thesortmethod instead of theglobmethod.sortcan also take a block to define a comparison, but this block doesn't make sense in that context.Chaining
eachto getDir.glob("*.txt").sort.each {|f| p f}makes the block an argument to theeachmethod, which uses it likeglobdoes (running the block for each argument).