Home > Blockchain >  Obtain variable value as a Ruby expression in String
Obtain variable value as a Ruby expression in String

Time:08-24

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.

CodePudding user response:

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.

  •  Tags:  
  • ruby
  • Related