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

Danny has posted 1 posts at DZone. View Full User Profile

Load Properties From Properties File Into Hash

01.29.2006
| 15257 views |
  • submit to reddit
        Loads properties from a file with lines formatted as 'key=value' into a Hash. Comments (lines starting with #) are skipped, as are lines starting with =. Empty property values (lines ending with =) and property values containing = are included in the Hash.

  def load_properties(properties_filename)
    properties = {}
    File.open(properties_filename, 'r') do |properties_file|
      properties_file.read.each_line do |line|
        line.strip!
        if (line[0] != ?# and line[0] != ?=)
          i = line.index('=')
          if (i)
            properties[line[0..i - 1].strip] = line[i + 1..-1].strip
          else
            properties[line] = ''
          end
        end
      end      
    end
    properties
  end