0

If I have a variable of a basic String/integer/float value, or a hash/array of these basic values, how to get its expression as a String?

If it is a string, I want '"foo"'. If it is an Integer, I want "1".

Basically I want the opposite of eval(). Currently I use inspect but it feels fragile.


Update:

I need to take user input, and output a .rb file containing that input. For exmple this erb file:

a = <%= variable %>

So if a user input a string, then in the .rb file I need to include that string in Ruby expression, e.g. a = "foo" or a = 1.

3
  • 2
    Your question is not clear to me. If it is already a string then it would return that string, if it is already an integer then it would return that integer. Therefore I do not understand the problem you are trying to solve. Would you mind elaborating and adding better examples of inputs and the expected outputs? Commented Aug 21, 2022 at 7:32
  • 1
    Agreed. As far as I can tell, it sounds like #inspect is exactly what you want. Commented Aug 21, 2022 at 7:39
  • @spickermann I will receive a dynamic variable from user input, and output that as part of a .rb file. Therefore I need to have that value in Ruby expression form. Commented Aug 21, 2022 at 11:41

1 Answer 1

2

inspect is the closest built-in method available. For the types you listed (integer, float, string, array, and hash) its output resembles a literal that will evaluate to an equivalent object. It's the very same value you get from IRB when inspecting a value – those can be copy-and-pasted back into Ruby.

The only exceptions I'm aware of are Float::NAN and (+/-) Float::INFINITY which print as NaN and Infinity.

Note that you can't set any output options, though. For example, String#inspect will always use double quotes, regardless of its characters. Hash#inspect will always use the key => value "hash rocket" syntax even if all keys are symbols.

That said, a Ruby expression generated via inspect will work for those core objects but it might not generate the most succinct literals.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.