Re: ruby rookie needs help with mtime method of File

Stefano Crocco <[email protected]> Thu, 22 Aug 2019 21:06:49 +0200
Newsgroups gmane.comp.lang.ruby.general
Message-ID <31355431.cTrelUPfZm@linux>
On giovedì 22 agosto 2019 21:53:31 CEST Barry Kimelman wrote:
> I was looking at an example of the "mtime" method for a file and when I ran
> the example I received the following traceback
> 
> C:\barry\ruby>ruby dir3-glob.rb
> backtick1.rb
> Traceback (most recent call last):
>         2: from dir3-glob.rb:3:in `<main>'
>         1: from dir3-glob.rb:3:in `glob'
> dir3-glob.rb:6:in `block in <main>': undefined method `mtime' for
> "backtick1.rb":String (NoMethodError)
> 
> The source of my script is as follows
>      1 #!C:\Ruby\bin\ruby.exe -w
>      2
>      3 Dir.glob("*.rb") {|file|
>      4  # do something with the file here
>      5  puts file
>      6  mtime = file.mtime
>      7  new_filename = "#{mtime.year}-#{mtime.month}-#{mtime.day}.wma"
>      8  puts "Renaming #{filename} to #{new_filename} ..."
>      9 }
> 
> What have I done wrong?
> 

mtime is a method of the File class. However, Dir.glob doesn't pass to the 
block objects of class File, but only their names. This means that your 
variable file is not a File but a string. To use the mtime method, you need to 
create an instance of class File corresponding to the name in the file 
variable:

Dir.glob("*.rb") { |filename|
  file = File.new filename
  mtime = file.mtime
  ...
}

I hope this helps

Stefano



Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>