【问题标题】:how to display a nil which is in the arguments of a method?如何显示方法参数中的 nil?
【发布时间】:2021-02-13 19:07:13
【问题描述】:

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

好吧,我想知道如何在方法的参数中显示一个 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, 42, 21)
puts who_is_bigger(84, 42, 21)
puts who_is_bigger(42, 84, 21)
puts who_is_bigger(42, 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

【问题讨论】:

  • 你想返回最大的属性是什么?或者你想返回哪个参数的值为84

标签: ruby variables methods null arguments


【解决方案1】:

您需要在其他条件之前检查您的nil

def who_is_bigger(a, b, c)
  if [a, b, 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

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 2018-09-04
    • 2011-06-18
    • 2020-07-09
    • 2014-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多