Convert Permission String To Octal

June 04, 2015

Small ruby snippet for converting a permission string (ACL) to octal, eg. drwxrwxrw- to 776.

class FilePermission
  def self.convert_string_to_octal(s)
    s.chomp!
    s[0]='' # remove 'd'
  
    map = {'r' => 4, 'w' => 2, 'x' => 1, '-' => 0}
    octal = ""

    s.scan(/.../).each do |part|
      sum = 0
      part.chars.each { |char| sum += map[char] }
      octal << sum.to_s
    end
    octal
  end
end

puts FilePermission.convert_string_to_octal 'drwxrwxrw-'
puts FilePermission.convert_string_to_octal '-rwxrwxrw-'
puts FilePermission.convert_string_to_octal '-r--------'
Share this post on Twitter
Morten Møller Riis

By Morten Møller Riis

I am a programmer, sysadmin, devops. I work for Gigahost in Copenhagen, Denmark. I am based in Odense, Denmark.

Twitter   ·   LinkedIn   ·   E-mail