DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Return The Device Name

08.25.2010
| 1949 views |
  • submit to reddit
        This will return the name of the device on which the file resides on ...

class File::Stat
  class << self
    def device_name(file)
      Dir['/dev/*'].inject({}) { |h, v|
        h.update(File.stat(v).rdev => v)
      }.values_at(File.stat(file).dev).first || nil
    end
  end
end

Simple use-case:

(main):001:0> File::Stat.device_name('/etc/resolv.conf')
=> "/dev/sda3"

Please note that this code may not be portable enough as it relies on the content of /dev.