Stringify array for eval

I am preparing a line that will be eval'ed. The string will contain a sentence built from an existing one 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 a line ["a", "b", "c"].

Is there a more idiomatic way to do this? Array#to_sDon't cut it. Is there a way to assign a result from a method to a pvariable?

Thank!

+3
source share
3 answers

inspect should fulfill what you want.

>> a = %w(a b c)
=> ["a", "b", "c"]
>> a.inspect
=> "[\"a\", \"b\", \"c\"]"
+8
source

I may not understand you, but does it all look better?

>> a = %w[a b c]
=> ["a", "b", "c"]
>> r = "['#{a.join("', '")}']"
=> "['a', 'b', 'c']"
>> r.class
=> String

I guess I am confused by the need for eval, if only this part of something is beyond what I see here.

0
source

p- ?

p ( , puts) $stdout nil. , $stdout.

require 'stringio'

def capture_stdout
  old = $stdout
  $stdout = StringIO.new(output = "")
  begin
    yield
  ensure 
    # Wrapping this in ensure means $stdout will 
    # be restored even if an exception is thrown
    $stdout = old
  end
  output
end

output = capture_stdout do
  p "Hello"
end

output # => "Hello"

, ,

output = stringify(a)
0

All Articles