Quick Tip: Parsing a Config String in Ruby
Recently I came across the need to parse a bit of a config file, in this kind of format: “Category=filetype;…” Here is how one would do such a thing using split, inject and map.
raw_config = "Image=jpg,tiff,png;Document=docx,doc,pdf;Other=rb,cs,c;" config = raw_config.split(";").inject({}) do |result, fragment| type, extensions = fragment.split("=") result[type.strip.downcase.to_sym] = extensions.split(",").map{ |s| s.strip } result end
The result is a hash where you can get an array of the file extensions for a given category like this
config[:image]
and the resulting hash looks like this:
{ :image => ["jpg", "tiff", "png"], :document => ["docx", "doc", "pdf"], :other => ["rb", "cs", "c"] }
Let me know in the comments if you have a better way!
No Comments
No comments yet