How to manipulate a Hash object to String

I got a result from my app (web service) that I transform into a
Hash :

@return = Hash.from_xml(data).values.first

@return = {“Saved”=>“false”, “Rating”=>{“Comment”=>nil, “Error”=>"
missing"}, “Post”=>{“Title”=>nil, “Error”=>“missing”},
“Post”=>{“Description”=>nil, “Error”=>“missing”},
“XXX”=>{“YYYYY”=>nil, “ZZZZ”=>“zzzzzz”}}

I would like to convert this result into a string , getting only the
YYYYY: zzzzzz

like this one
“Comment: missing, Title: missing, Description: missing, YYYYY:
zzzzzz”

I am not very easy with Hash transformation, so a little bit help will
be appreciated

thanks

Erwin

Erwin wrote:

thanks

Erwin

It seems like you have some fairly specific data you need to put into
the string, so I don’t think you can do this in a very generic way.

However, if you know what keys you need, then taking values from a hash
and creating a string is pretty straightforward. I’m assuming here that
you only want to display the “Error” when the other value doesn’t exist:

return_string = “Comment: #{@return[“Rating”][“Comment”] ||
@return[“Rating”][“Error”]}, Title: #{@return[“Post”][“Title”] ||
@return[“Post”][“Error”]}” #…etc

But I noticed that you have two “Post” keys in your hash - one will
overwrite the other. You might want to see what you are really getting
back from the web service.

-Justin

Erwin wrote:

I got a result from my app (web service) that I transform into a
Hash :

@return = Hash.from_xml(data).values.first

@return = {“Saved”=>“false”, “Rating”=>{“Comment”=>nil, “Error”=>"
missing"}, “Post”=>{“Title”=>nil, “Error”=>“missing”},
“Post”=>{“Description”=>nil, “Error”=>“missing”},
“XXX”=>{“YYYYY”=>nil, “ZZZZ”=>“zzzzzz”}}

You seem to have more complex structure then just hash with single
value. If you had simple hash you could do something like this.

c = ‘’
@return.each_pair {|k,v| c << “#{k}: #{v},” }

You would also have to remove trailing ,

by
TheR

Damjan R. wrote:

c = ‘’
@return.each_pair {|k,v| c << “#{k}: #{v},” }

You would also have to remove trailing ,

by
TheR

irb(main):001:0> {“1”=>“2”, “3”=>4}.map{|k,v| “#{k}:#{v}”}.join(",")
=> “1:2,3:4”
irb(main):002:0>

no trailing comma… :slight_smile:

hth

ilan