【发布时间】:2017-01-14 17:19:42
【问题描述】:
以下条件语法在不使用puts的情况下在irb中显示字符串'is true'
irb(main):001:0> if true
irb(main):002:1> 'is true'
irb(main):003:1> else
irb(main):004:1* 'is false'
irb(main):005:1> end
=> "is true"
...然而,当我在脚本中调用相同的语法并从命令行运行它时,它会被忽略。为什么?
# Odd behaviour:
puts "Why do only two of the three conditionals print?"
# This doesn't put anything to screen:
if true
'is true_1'
else
'is false'
end
puts "Seriously, why? Or better yet: how?"
# But this does:
if true
puts 'is true_2'
else
puts 'is false'
end
# And this works without "puts":
def truthiness
if 1.send(:==, 1)
'is true_3'
else
'is false'
end
end
puts truthiness
puts "Weird."
当我将它作为脚本运行时,它会显示:
"Why do only two of the three conditionals print?
Seriously, why? Or better yet: how?
is true_2
is true_3
Weird."
FWIW,我正在关注 Sandi Metz 的演讲“Nothing is Something”
https://youtu.be/zc9OvLzS9mU
...并听这个:
https://youtu.be/AULOC--qUOI
道歉,因为我是 Ruby 新手,并试图了解它是如何做的。
编辑:
有用资源:
http://ruby-doc.org/core-2.3.1/Kernel.html#method-i-puts
https://softwareengineering.stackexchange.com/questions/150824/is-the-puts-function-of-ruby-a-method-of-an-object
【问题讨论】:
-
irb 打印出您键入的每个命令的返回值。有点像交互式调试器。运行脚本时,它不会输出任何内容,除非使用
puts或类似名称告知。
标签: ruby return-value irb puts