6
\$\begingroup\$

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.

\$\endgroup\$

3 Answers 3

9
\$\begingroup\$

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
\$\endgroup\$
0
2
\$\begingroup\$

Is this a method or a classmethod? since it's not using anything of the instance, it probably should be a classmethod. I'd write:

def self.parser(strval)
  strval.split(';').map do |pair|
    key, value = pair.split('=')
    [key, value.to_i]
  end.to_h
end
\$\endgroup\$
2
\$\begingroup\$

You can simplify what you have by using each rather than map and performing all operations in one block:

def parser input
    output = {}
    input.split(';')
         .each do |s|
            k,v = s.split('=')
            output[k] = v.to_i
          end
    output
 end

Further simplification is possible by using Enumerable#each_with_object:

def parser input
  input.split(';')
       .each_with_object({}) do |s,output|
          k,v = s.split('=')
          output[k]=v.to_i
        end
 end

Here's another way:

def parser input
  input.split(/=|;/).each_slice(2)
                    .with_object({}) { |(k,v),h| h[k]=v.to_i }
end
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.