则在Ruby中返回什么

则在Ruby中返回什么

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

问题描述

我的理解是,ruby返回函数中求值的最后一条语句.如果函数以 if 语句结尾为假

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中返回什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 09:47