Ruby 的 to_s 方法问题(来自 Ax 书第 2 版) [英] Ruby's to_s method question (from Axe book 2nd edition)

查看:28
本文介绍了Ruby 的 to_s 方法问题(来自 Ax 书第 2 版)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据ax book(第2版),我们可以使用to_s如下.

<前>班歌def to_s歌曲"结尾结尾歌曲 = Song.new()歌曲.to_s

但是,它没有给我任何东西,为了向标准输出打印一些东西,我应该运行

<前>def to_sp歌曲"结尾

自编写本书时的 ruby​​ 1.8.2 以来有什么变化吗?我的 ruby​​ 版本信息是 1.8.7 for Mac.

ruby 1.8.7 (2009-06-08 patchlevel 173) [universal-darwin10.0]

解决方案

Pickaxe 书使用了一个常见的符号,例如

song.to_s歌曲:我的路——辛纳屈(225)"

表示Song: My Way--Sinatra (225)"是左边表达式的值.但是,除非您明确使用 puts,否则它不会被打印出来.

to_s 在对象上的适当实现将返回该对象的字符串表示(例如一个人的姓名或博客文章的标题和 ID),但实际上不会有任何副作用本身(例如输出某些东西.)

如果您使用 irb,交互式 Ruby 解释器会为您打印出每个表达式的值,而无需显式 puts.例如

$ irbirb(main):001:0>2 + 2=>4

According to the axe book (2nd edition), we can use to_s as follows.

class Song
  def to_s
    "Song"
  end
end

song = Song.new()
song.to_s

But, it doesn't give me anything, in order to print something to the stdout, I should run

  def to_s
    p "Song"  
  end

Is there any change since the ruby 1.8.2 when the book was written for? My ruby version info is 1.8.7 for Mac.

ruby 1.8.7 (2009-06-08 patchlevel 173) [universal-darwin10.0]

解决方案

The Pickaxe book uses a common notation of e.g.

song.to_s"Song: My Way--Sinatra (225)"

to indicate that "Song: My Way--Sinatra (225)" is the value of the expression on the left. However it isn't printed out unless you explictly use a puts.

An appropriate implementation of to_s on an object will return a string representation of that object (e.g. the name for a person or the title and ID for a blog post) but won't actually have any side effects itself (such as outputting something.)

If you use irb, the interactive Ruby interpreter it prints out the value of each expression for you without an explicit puts. e.g.

$ irb
irb(main):001:0> 2 + 2
=> 4

这篇关于Ruby 的 to_s 方法问题(来自 Ax 书第 2 版)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆