patternrubyMinor
Parsing a string of the form "key1=value1;key2=value2;" into a Hash
Viewed 0 times
theintovalue2hashkey1parsingkey2value1formstring
Problem
I need to parse the following input string into a hash table with the following format:
Input:
Output:
My solution:
Any insight is appreciated.
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
The function name could probably be improved.
When using
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
]
endCode Snippets
def to_hash(str)
Hash[
str.split(';').map do |pair|
k, v = pair.split('=', 2)
[k, v.to_i]
end
]
endContext
StackExchange Code Review Q#80572, answer score: 9
Revisions (0)
No revisions yet.