HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Parsing a string of the form "key1=value1;key2=value2;" into a Hash

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theintovalue2hashkey1parsingkey2value1formstring

Problem

I need to parse the following input string into a hash table with the following format:

Input:

'1001=23;1001B=5;1002=0;1003=5;'


Output:

=> {'1001'=>23,'1001B'=>5,'1002'=>0,'1003'=>5}


My solution:

def parser input
  output = {}
  input.split(';').map {|ar| ar.split('=')}.each {|id, c| output[id]=c.to_i}
  output
end
parser '1001=23;1001B=5;1002=0;1003=5;'


Any insight is appreciated.

Solution

You can make it a single expression by taking advantage of Hash[[key, value], …] (available since Ruby 1.9).

The function name could probably be improved.

When using String#split, I consider it good practice to limit the number of splits whenever a limit may be applicable. Here, you wouldn't be able to tolerate a second = sign within each key=value string, so you should use pair.split('=', 2).

def to_hash(str)
  Hash[
    str.split(';').map do |pair|
      k, v = pair.split('=', 2)
      [k, v.to_i]
    end
  ]
end

Code Snippets

def to_hash(str)
  Hash[
    str.split(';').map do |pair|
      k, v = pair.split('=', 2)
      [k, v.to_i]
    end
  ]
end

Context

StackExchange Code Review Q#80572, answer score: 9

Revisions (0)

No revisions yet.