Search code examples
rubyenumerable

Understanding find function on an Enumerable in Ruby


I am reading "Practical Ruby for System Administration" by Andre Ben Hanou, which has a one-liner that lists all files in a directory whose size is bigger than 1KB and then sorted by the modification date.

ruby -e 'puts Dir["*"].find { |f| File.size(f) > 1024 }.sort_by{|f| File.mtime(f)}'

I think that it should be select instead of find.

According to the documentation for find, it returns the first for which the block is not false. So, find will never return a list of files in any case. It's like the 19th page in the book, and I am completely new to Ruby, and I think that the author is wrong because the command in the book gives me an error already.

shadyabhi@archlinux /tmp $ ruby -e 'puts Dir["*"].find { |f| File.size(f) > 1024 }.sort_by{|f| File.mtime(f)}'
-e:1:in `<main>': undefined method `sort_by' for "mysql-security-excerpt-5.1-en.pdf":String (NoMethodError)
shadyabhi@archlinux /tmp $ 

Can anyone confirm that the author is wrong or I am just being plain stupid?


Solution

  • You are right, it should be .select (or its alias .find_all, which may be the reason for this error).

    In this case the block is evaluated for each object, here is a tutorial: http://www.tutorialspoint.com/ruby/ruby_blocks.htm