Home > Blockchain >  Ruby on Rails: How to pluck hash from a string
Ruby on Rails: How to pluck hash from a string

Time:07-28

I have a record of class String something like:

"{'1'=>'abc', '2'=> 'def'}"

but from this i need this in class Hash, something like:

{'1'=>'abc', '2'=> 'def'}

how to convert like this?

Edit: in my case i was getting this from CSV from other service where they were converting Hash into String before sending, so i asked them to send it using Base64.encode64 and now i am able to decode and get it in Hash format.

CodePudding user response:

If you trust that the data is not nefarious you can write

h = eval "{'1'=>'abc', '2'=> 'def'}"
  #=> {"1"=>"abc", "2"=>"def"}

See Kernel#eval.

CodePudding user response:

This answer might not related to the question that i asked, but this is what solved my case, since other service was sending few Hash records in CSV format, they were converting the Hash to String before posting it to me. So i asked them to use Base64.encode64 and send the encoded string in CSV.

Base64.encode64({'1'=>'abc', '2'=> 'def'}.to_json).delete("\n")
  #=> "eyIxIjoiYWJjIiwiMiI6ImRlZiJ9"

and when i get the string i am converting it back to Hash something like

JSON.parse(Base64.decode64("eyIxIjoiYWJjIiwiMiI6ImRlZiJ9"))
  #=> {"1"=>"abc", "2"=>"def"}
  • Related