What is the exact role of eval in Ruby? And I heard it's not good to use it. Is that true?

Asked 2 years ago, Updated 2 years ago, 41 views

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

2022-09-22 16:00

1 Answers

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


2022-09-22 16:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.