如果评估的最后一个语句是 If 语句,Ruby 会返回什么 [英] What is Returned in Ruby if the Last Statement Evaluated is an If Statement

查看:17
本文介绍了如果评估的最后一个语句是 If 语句,Ruby 会返回什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解是 ruby​​ 返回函数中评估的最后一条语句.如果函数以 if 语句结束,结果为 false

My understanding is that ruby returns the last statement evaluated in a function. What if the function ends with an if statement that evaluates to false

def thing(input)
  item = input == "hi"
  if item
    []
  end
end

puts thing("hi").class #> Array
puts thing("not hi").class #> NilClass

我喜欢这个功能(如果语句为 false,则返回 nil),但为什么不返回 false(从赋值给 item)?

I like this functionality (returning nil if the statement is false), but why isn't false returned (from the assignment to item)?

推荐答案

如果你的 if 语句没有运行任何代码,则返回 nil,否则返回运行的代码.Irb 是试验这些东西的好工具.

If your if statement doesn't result in any code being run, it returns nil, Otherwise, it returns the value of the code that was run. Irb is a good tool to experiment with such stuff.

irb(main):001:0> i = if false then end
=> nil
irb(main):002:0> i = if true then end
=> nil
irb(main):007:0> i = if false then "a" end
=> nil
irb(main):008:0> i = if false then "a" else "b" end
=> "b"

这篇关于如果评估的最后一个语句是 If 语句,Ruby 会返回什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆