Skip to content

Instantly share code, notes, and snippets.

@JvGinkel
Created March 20, 2018 17:46
Show Gist options
  • Save JvGinkel/8dad3cbff2bd20ee27a1cbccd2b7a1b0 to your computer and use it in GitHub Desktop.
Save JvGinkel/8dad3cbff2bd20ee27a1cbccd2b7a1b0 to your computer and use it in GitHub Desktop.
Ruby convert ini file to a hash
def i2h_parse_line(line)
line.strip.split(';').first =~ %r{^\[([a-zA-Z0-9]+)\]$|^([a-zA-Z0-9\.]+)\s*\=\s*([a-zA-Z0-9\.]+)$}
data = [Regexp.last_match(1), Regexp.last_match(2), Regexp.last_match(3)]
data
end
def ini2hash(filename)
ini = {}
cur_section = nil
File.open(filename).each do |line|
data = i2h_parse_line(line)
cur_section = data[0] unless data[0].nil?
ini[cur_section] = {} unless data[0].nil?
ini[cur_section].merge!(data[1] => data[2]) if data[1]
end
ini
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment