下面的条件语法显示irb中的字符串“是真”而不使用puts
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"...yet当我在脚本中调用相同的语法并从命令行运行它时,它将被忽略。为什么?
# 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的演讲“什么都不是什么”https://youtu.be/zc9OvLzS9mU ...and在听这段话:https://youtu.be/AULOC--qUOI道歉,因为我对Ruby很陌生,并且试图思考它是如何做到的。
编辑:有用的资源:
http://ruby-doc.org/core-2.3.1/Kernel.html#method-i-puts
发布于 2016-09-07 06:41:14
这里的IRB输出显示操作的返回值,这不一定是在执行过程中打印到STDOUT (即终端)的内容。
您的脚本正在丢弃返回值,您必须这样做:
val = if true
'is true_1'
else
'is false'
end
puts valhttps://stackoverflow.com/questions/39362740
复制相似问题