matanco matanco - 6 months ago 36
Ruby Question

How to check if a string contain valid hash

i encounter a problem when i want to validate the input string if it contain a valid hash before execute eval on it, for example:

if i run eval it return a correct hash, but if i run eval on this string
i get syntax error of expected token:

(eval):1: syntax error, unexpected end-of-input, expecting '}' {:redirect=>true ^

i did tried some basic validation but no luck so far.

so basically what i want to know is how to validate a that a string contain correct hash format.


You can't tell without actually parsing it as Ruby, and (assuming you trust the string), the simplest way of parsing it is to simply do the eval call, and handle the exception:

  hash = eval(string)
rescue SyntaxError
  # It's not valid

This is precisely what exceptions are for, instead of littering your code with checks for whether operations will succeed, you just perform the operations, and handle errors that occur.