Ruby 关键词 while 有没有返回值?

runup · 2015年12月30日 · 最后由 runup 回复于 2016年01月22日 · 2919 次阅读

文件 demo.rb 中的代码如下,其中 testfile 文件中的文字为“this is the test” ARGV << "testfile" print while gets 代码来自于Ruby core 文档的 gets 方法 终端执行 demo.rb,返回值为:this is the test,说明 print 打印的是整个 testfile 的内容,也就是 gets 的值,是否就是说 while gets 返回的就是 gets 的值。但是我的理解 while 是做判断,如果 gets 为 nil,则 while gets 判断为 false,print 值为 false,如果 gets 不为 nil,则 while gets 判断为 true,print 值为 true。但是实际结果与我的理解不同,请问,问题在哪里?

看文档要仔细, gets:

Returns (and assigns to $_) the next line from the list of files in ARGV (or $*)...

print:

If no arguments are given, prints $_.

#1 楼 @nowherekai 非常感谢指出问题,这两句话我理解,在这里 gets 和 ARGV 指向相同的字符串内容,我的疑惑是 while 的作用,while 这里是做判断,返回值应该是 true 或者 false,所以 print 打印的应该也是 while gets 的返回值才对。

#2 楼 @qinfanpeng 能不能请帮忙看下我的理解问题在哪里?感谢。

while 不是判断,只是条件循环,它判断 gets 的返回值,如果 gets 返回 nil 或者 false 就跳出循环。你的代码和下面的代码是等价的

ARGV << "testfile"

loop do
  gets ? print : break
end

What you think your code is:

print (while gets)

Actually, your code is the same as this:

while gets
  print
end

Try this code, it should print nil.

a = (print while gets)
p a

谢谢楼上各位的指点,感激。

#6 楼 @emayej 这语法糖我自己都反应不过来了…… 私以为这种语句不用 one liner 可能会更清晰易懂。

补充一句,这句话应该理解成:

begin
  print
end while gets

#1 楼 @nowherekai @qinfanpeng 为什么这里的 print 方法是 IO 中的 print 实例方法,而不是 Kernel 中的 print 方法?

是 kernel 中的吧?kernel 中的 print 最终也会调用 IO#print 的

#11 楼 @nowherekai kernel 中的 print 最终也会调用 IO#print 的这是为什么?

需要 登录 后方可回复, 如果你还没有账号请 注册新账号