gpt4 book ai didi

ruby - 我的 Ruby 条件是什么?

转载 作者:数据小太阳 更新时间:2023-10-29 08:36:07 24 4
gpt4 key购买 nike

以下条件语法在不使用 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 输出显示的是操作的返回值,这不一定是执行期间打印到 STDOUT(即终端)的内容。

您的脚本只是丢弃了返回值,您必须这样做:

val = if true
'is true_1'
else
'is false'
end

puts val

关于ruby - 我的 Ruby 条件是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39362740/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com