user836087 user836087 - 1 month ago 4x
Ruby Question

Parse unpleasant string in ruby to derive a condition

I have a response string that gets returned from a webservice that isn't JSON exactly, nor any other kind of hashable object, I can serialize.
I'm new to regex so I'm trying to learn how I can extract the needed pieces for my ruby code.

The response string looks like the below:

if (typeof partialResult !== "undefined") {
partialResult({"Q":"laptop bag","R":[["laptop
bag",[["Electronics",3944]]],"laptop bags for 15.6 inch
laptops","laptop bags for women","laptop bag 15.6","laptop bags for
17.3 in laptops","rolling laptop bag","laptop bag with wheels","laptop bag 17\""]}) }

In ruby, I'd like to check whether "Q":"laptop bag" and the result of "R":[["laptop bag" are equal. This should return a true because both Q and R = "laptop bag".

The string is so horrendous, I'm not sure how to go about comparing the two. I don't know much regex so that's also a hindrance. Thank you in advance for any help you can provide.


The parameter passed to partialResult method should be valid json. You can use regex, to extract that string.

require 'json'
hsh = JSON.parse str.scan(/partialResult\((.*)\)/)[0][0]
#=> {"Q"=>"laptop bag", "R"=>[["laptop bag", [["Electronics", 3944]]], "laptop bags for 15.6 inch laptops", "laptop bags for women", "laptop bag 15.6", "laptop bags for 17.3 in laptops", "rolling laptop bag", "laptop bag with wheels", "laptop bag 17\""]} 

To check for a common string

hsh["R"].flatten && hsh["Q"].flatten
#=> "laptop bag"