给定已定义和未定义的变量,我们必须检查变量是否已定义。
Ruby提供了多种方法来检查代码中变量的存在。我们在该程序中包括了其中两个。方式和返回类型不同。由您自己决定如何采取措施使逻辑更好地用于漂亮的程序代码。现在,让我们介绍两种方法。
puts:
此方法用于向用户显示某种消息。
.defined?:
此方法返回变量的类型,例如local或instance。如果在程序代码中未定义变量,它将不返回任何内容。
.include?:
此方法返回的值为true或false。它要求变量的类型知道它是否已定义。。包括?该方法具有许多功能。它也用于数组中。
方法1:
=begin Ruby program to check whether a variable is defined or not. =end var1=9 var2=89 var3=89 str="apple" str2="Mango" puts defined?(var1) puts defined?(var2) puts defined?(var3) puts defined?(str33) #什么都不会显示 puts defined?(str2) #通过if-else检查 if (defined?(var1)) puts "var1 is defined" else puts "var1 is not defined" end if (defined?(var2)) puts "var2 is defined" else puts "var2 is not defined" end if (defined?(var3)) puts "var3 is defined" else puts "var3 is not defined" end if (defined?(var33)) puts "var33 is defined" else puts "var33 is not defined" end if (defined?(str)) puts "str is defined" else puts "str is not defined" end if (defined?(str1)) puts "str1 is defined" else puts "str1 is not defined" end if (defined?(str2)) puts "str2 is defined" else puts "str2 is not defined" end
输出结果
local-variable local-variable local-variable local-variable var1 is defined var2 is defined var3 is defined var33 is not defined str is defined str1 is not defined str2 is defined
方法2:
=begin Ruby program to check whether a variable is defined or not. =end var1=9 var2=89 var3=89 str="apple" str2="Mango" puts local_variables.include?(:var1) puts local_variables.include?(:str22) puts local_variables.include?(:str2) puts local_variables.include?(:var3) puts local_variables.include?(:str) puts local_variables.include?(:str2245)
输出结果
true false true true true false