There is a problem that I want to use eval while working on Rails. It was when I received JSON input and saved it in DB.
I received the JSON Array and saved it in DB, so it's a string
"[1, 2, 3]"
is saved like this. So I saved it after doing val
.
As I searched about eval, I saw a post that it is better not to use eval.
What method should I use instead of eval?
.
ruby eval
val is used to dynamically create/evaluate/execute syntax
You can convert it into a string (#to_json in the standard library json) and parse the loaded string to JSON.parse.
# rspec_test on irb
require 'json'
require 'rspec'
include RSpec::Matchers
json_str = {hi: "sup", yo: "hey"}.to_json
# 1. Parsing strings to Hash
parsed = JSON.parse(json_str )
expect( parsed.class ).to eq Hash
expect( parsed["hi"] ).to eq "sup"
# 2. Convert Hash to #to_json string
expect( parsed.to_json ).to eq json_str
expect( parsed.to_json.class ).to eq String
827 M2 Mac fails to install rbenv install 3.1.3 due to errors
1300 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
894 Uncaught (inpromise) Error on Electron: An object could not be cloned
803 Error in x, y, and format string must not be None
790 GDB gets version error when attempting to debug with the Presense SDK (IDE)
© 2025 OneMinuteCode. All rights reserved.