Thursday, December 12, 2013

Displaying Escaped Characters Better with Back References

Have you ever received strings with literal characters, like the one below, that just look like a lot of noise?

Start with this


"body"=>"\"{\\\"class\\\":\\\"MigrationMgr\\\",\\\"args\\\":[null,\\\"migrate_product\\\",1,3]}\""

A little better

Open up an IRB or Ruby command console and when you use puts, it looks a little better...

[1] pry(main)> s=< "\"\"{\\\"class\\\":\\\"MigrationMgr\\\",\\\"args\\\":[null,\\\"migrate_product\\\",1,3]}\"\"\n"
[2] pry(main)> puts s
""{\"class\":\"MigrationMgr\",\"args\":[null,\"migrate_product\",1,3]}""
But it's still not as clean as you'd like.

Back References to the Rescue

First, create the back references

back_refs = {
   '\"' => '',
   "\\" => ''''
}


Next, use gsub and regex groupings to replace the back references with the desired, simpler characters.

hash_var['body'].gsub(/([\"\\])/) { back_refs[$1] }.gsub(',', ', ')

Result

Now, we have nicely formatted data that we can use for display purposes.

{class:MigrationMgr, args:[null, migrate_product, 1, 3]}

No comments:

Post a Comment