1

I have a Hash that looks like this:

{ 'key1' => 'value1', 'key2' => ['value2', 'value3']}

And I need to create a string that will look like this:

key1/value1;key2/value2,value3

So, the pattern is key/value and ';' as separator. And if there are more than one value do value1,value2 ',' is the separator.

Here is what I have so far:

def build_string params
        url_params = ''
      params.each do |key, value|
        url_params += key
        url_params += '/'
        if value.kind_of? Array
          url_params += value.join(",") 
        else
          url_params += value
        end
        url_params += ';'
      end
      return url_params
    end

The problem is that this is adding a ';' at the end of the string, and I just want it as separator of each hash element. I have thought of doing a join(';'), but I am not sure how to do the rest of the operations beforehand.

1 Answer 1

4
params.map { |k, v| "#{k}/#{[v].flatten.join(',')}" }.join(';')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.