我的 Ruby 条件是什么?
What condition is my Ruby conditional in?
以下条件语法在不使用 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 输出显示了操作的 return 值,这不一定是执行期间打印到 STDOUT(即终端)的值。
您的脚本只是丢弃了 return 值,您必须这样做:
val = if true
'is true_1'
else
'is false'
end
puts val
以下条件语法在不使用 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"
...然而,当我在脚本中调用相同的语法并从命令行调用 运行 时,它会被忽略。为什么?
# 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 输出显示了操作的 return 值,这不一定是执行期间打印到 STDOUT(即终端)的值。
您的脚本只是丢弃了 return 值,您必须这样做:
val = if true
'is true_1'
else
'is false'
end
puts val