Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stringify array for eval

Tags:

ruby

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!

like image 765
Martin Carpenter Avatar asked Apr 18 '26 06:04

Martin Carpenter


1 Answers

inspect should accomplish what you are wanting.

>> a = %w(a b c)
=> ["a", "b", "c"]
>> a.inspect
=> "[\"a\", \"b\", \"c\"]"
like image 146
Aaron Hinni Avatar answered Apr 21 '26 02:04

Aaron Hinni