I'm preparing a string that will be eval'ed. The string will contain a clause built from an existing Array. I have the following:
def stringify(arg)
return "[ '" + arg.join("', '") + "' ]" if arg.class == Array
"'#{arg}'"
end
a = [ 'a', 'b', 'c' ]
eval_str = 'p ' + stringify(a)
eval(eval_str)
which prints the string ["a", "b", "c"].
Is there a more idiomatic way to do this? Array#to_s doesn't cut it. Is there a way to assign the output from the p method to a variable?
Thanks!
inspect should accomplish what you are wanting.
>> a = %w(a b c)
=> ["a", "b", "c"]
>> a.inspect
=> "[\"a\", \"b\", \"c\"]"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With