将File :: Stat转换为hash ruby

shi*_*vam 5 ruby

想知道有没有办法转换输出

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>
Run Code Online (Sandbox Code Playgroud)

哈希?

Jac*_*own 1

我认为没有File::Stat提供这样的方法。您可以像这样对类进行猴子修补以提供类似的内容:

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
Run Code Online (Sandbox Code Playgroud)

这会将对象的所有实例方法(仅在 中定义的实例方法File::Stat,没有祖先)拉入散列。它省略了任何带有参数的方法。