Wondering is there any way to convert the output of
File.stat("/tmp/somefile")
=> #<File::Stat dev=0x80a, ino=553198, mode=0100664, nlink=1, uid=1000, gid=1000, rdev=0x0, size=0, blksize=4096, blocks=0, atime=Wed Aug 06 19:04:30 +0530 2014, mtime=Wed Aug 06 19:04:30 +0530 2014, ctime=Wed Aug 06 19:04:30 +0530 2014>
to a hash?
I don't think File::Stat
provides such a method. You could monkey-patch the class like this to provide something similar:
File::Stat.class_eval do
def to_hash
meths = self.methods - self.class.superclass.instance_methods - [__callee__]
meths.each_with_object({}) do |meth, acc|
acc[meth.to_s] = self.send(meth) if self.method(meth).arity == 0
end
end
end
This pulls all the object's instance methods (and only those defined in File::Stat
, no ancestors) into a hash. It omits any methods that take arguments.
Not sure if this is the prettiest solution, but it works:
h = Hash.new
f = File.stat('file.rb')
f.methods[1..17].each do |m|
h[m] = f.send m
end
h
#=> {:dev=>64770, :dev_major=>253, :dev_minor=>2, :ino=>1315340, :mode=>33204, :nlink=>1, :uid=>1000, :gid=>1000, :rdev=>0, :rdev_major=>0, :rdev_minor=>0, :size=>1553, :blksize=>4096, :blocks=>8, :atime=>2014-02-17 17:43:13 +0100, :mtime=>2014-02-17 17:43:13 +0100, :ctime=>2014-02-17 17:43:13 +0100}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With