ruby - Ruby 中的直接字符串表示

标签 ruby

是否有一种简单的方法来获取 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/

相关文章:

sql - 同一天创建的记录数

ruby-on-rails - 为什么在 rails 中的 blob 数据类型的情况下数据库迁移失败?

ruby - 在 Ruby 中自动记录异常

ruby-on-rails - assert_equal 语法

ruby-on-rails - 如何从 Rails 4 中的辅助测试访问 Controller 辅助方法?

ruby - 如何在 Ruby 中用数组替换字符串参数?

ruby - 将 ruby​​ 和 ruby​​gems 移动到自定义路径中

Ruby:为什么 nil.to_s 返回 "",但 nil.inspect 返回 "nil"

php - 在 Rails 中处理数百个同时请求

ruby-on-rails - Devise 和 Rspec - 为未经身份验证的用户测试重定向时 Controller 测试出错