这是我在这里的第一篇文章,我是一个超级初学者,我想解决一个练习。
我想知道如何在方法的参数中显示一个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
您需要在其他条件之前在开头进行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