代码之家  ›  专栏  ›  技术社区  ›  Martin Carpenter

用于eval的字符串化数组

  •  3
  • Martin Carpenter  · 技术社区  · 16 年前

    我正在准备一根绳子 eval 'ed。字符串将包含从现有的 Array . 我有以下几点:

    def stringify(arg)
        return "[ '" + arg.join("', '") + "' ]" if arg.class == Array
        "'#{arg}'"
    end
    
    a = [ 'a', 'b', 'c' ]
    eval_str = 'p ' + stringify(a)
    eval(eval_str)
    

    打印字符串 ["a", "b", "c"] .

    有没有更惯用的方法? Array#to_s 不会切的。是否有方法分配 p 方法到变量?

    谢谢!

    3 回复  |  直到 16 年前
        1
  •  8
  •   Aaron Hinni    16 年前

    inspect 应该完成你想要的。

    >> a = %w(a b c)
    => ["a", "b", "c"]
    >> a.inspect
    => "[\"a\", \"b\", \"c\"]"
    
        2
  •  0
  •   dylanfm    16 年前

    我可能误解了你,但这看起来更好吗?

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

    我想我对撤离的必要性感到困惑,除非这是我在这里所看到的以外的东西的一部分。

        3
  •  0
  •   Xavier Shay    16 年前

    有办法分配输出吗 从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)