热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

什么是ruby中的__repr__等价?-What'sthe__repr__equivalenceinruby?

The__repr__functionofpythonisfancyasitiscalledwhenprintOBJECTisusedautomatically.py

The __repr__ function of python is fancy as it is called when print OBJECT is used automatically.

python的__repr__函数很自然,因为在自动使用print OBJECT时会调用它。

Is there a ruby equivalence for it? I thought it was to_s, but, I had p OBJECT doesn't seem to call the to_s method.

它有红宝石等价吗?我以为是to_s,但是,我有p OBJECT似乎没有调用to_s方法。

Added

I got something wrong, p OBJECT seems to call to_s method as follows. I got some hints from my the answers to my other question. - Ruby's to_s method question (from Axe book 2nd edition)

我弄错了,p OBJECT似乎调用to_s方法如下。我从我对其他问题的答案中得到了一些提示。 - Ruby的to_s方法问题(来自Axe第2版)

# Sample code from Programing Ruby, page 24
class Song
  def to_s
    "Song"
  end
end

class Songson "
  end
end

sOng= Songson.new()
p song

2 个解决方案

#1


10  

  obj.inspect => string

Returns a string containing a human-readable representation of obj. If not overridden, uses the to_s method to generate the string.

返回包含obj的人类可读表示的字符串。如果未覆盖,则使用to_s方法生成字符串。

   [ 1, 2, 3..4, 'five' ].inspect   #=> "[1, 2, 3..4, \"five\"]"
   Time.new.inspect                 #=> "Wed Apr 09 08:54:39 CDT 2003"

 obj.to_s => string

Returns a string representing obj. The default to_s prints the object‘s class and an encoding of the object id. As a special case, the top-level object that is the initial execution context of Ruby programs returns ``main.’‘

返回表示obj的字符串。默认的to_s打印对象的类和对象id的编码。作为一种特殊情况,作为Ruby程序的初始执行上下文的顶级对象返回“main”。

source

#2


3  

p object uses #inspect.

p对象使用#inspect。


推荐阅读
author-avatar
上帝的宝贝1
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有