是否有一种简单的方法来获取 Ruby 构造的直接字符串表示形式?
例如:
a = [:foo, :bar]
当调用 a.to_s
时,我得到:
"foobar"
我正在寻找的是:
"[:foo, :bar]"
最佳答案
您使用的是什么版本的 Ruby?使用 Ruby 1.9 我得到:
irb(main):002:0> a = [:foo, :bar]
=> [:foo, :bar]
irb(main):003:0> a.to_s
=> "[:foo, :bar]"
irb(main):004:0> a.inspect
=> "[:foo, :bar]"
编辑正如@fl00r 所指出的,在 1.8.7 中您可以使用inspect
。一般来说,inspect
应该提供人类可读的字符串,即使 to_s
没有。来自ruby docs :
obj.inspect → string
Returns a string containing a human-readable representation of obj. If not overridden and no instance variables, uses the to_s method to generate the string.
to_s不声称人类可读。
关于ruby - Ruby 中的直接字符串表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5452562/