微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何显示方法参数中的nil?

如何解决如何显示方法参数中的nil?

这是我在这里的第一篇文章,我是一个超级初学者,我想解决一个问题。

好吧,我想知道如何在方法的参数中显示nil。 这是我尝试的代码,但是预期结果不符合我的期望,您能帮我吗?谢谢。

def who_is_bigger(a,b,c)
  max_number = 84
  the_nil = c
  if max_number == a
    puts "a is bigger"
  elsif max_number == b
    puts "b is bigger"
  elsif max_number == c
    puts "c is bigger"
  elsif the_nil == nil
    puts "nil detected"
  else
    puts "nil detected"
  end
end
  
puts who_is_bigger(84,42,nil)
puts who_is_bigger(nil,21)
puts who_is_bigger(84,21)
puts who_is_bigger(42,84,21,84)

我的终端将其退回;

a is bigger
nil detected
a is bigger
b is bigger
c is bigger

但是我想要这个;

nil detected
nil detected
a is bigger
b is bigger
c is bigger

解决方法

您需要在其他条件之前先进行nil检查。

def who_is_bigger(a,b,c)
  if [a,c].include?(nil)
    puts "nil detected"
    return
  end
  max_number = 84
  if max_number == a
    puts "a is bigger"
  elsif max_number == b
    puts "b is bigger"
  elsif max_number == c
    puts "c is bigger"
  else
    puts "nil detected" # this should really be max_number not found
  end
end

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。