Ruby项目中含case语句的方法调用仅返回:identify_class问题求助
解决Ruby方法调用返回
:identify_class的问题 刚接触Ruby就遇到这种小问题很正常,别担心!根据你描述的情况,控制台返回:identify_class而不是预期的输出字符串,大概率是下面两种情况之一:
1. 方法最后一行意外返回了符号:identify_class
Ruby方法默认会返回最后一行代码的执行结果,如果你的方法结尾不小心加了这个符号,那调用方法时自然会返回它。比如你可能写了这样的代码:
def identify_class(str) case str when "student" "This is a Student class" when "teacher" "This is a Teacher class" end # 不小心加了这一行! :identify_class end
解决方法很简单:删掉最后一行的:identify_class,确保case语句是方法的最后一行——因为case本身会返回匹配分支的结果,这样方法就会返回你预期的字符串了。
2. 你调用的是符号而非方法
如果你的方法定义是正常的,但调用时不小心写成了:identify_class而不是identify_class("你的字符串"),那控制台当然会直接返回这个符号。比如:
# 正确调用 identify_class("student") # 错误调用(会返回符号) :identify_class
检查一下你的调用代码,确保是调用方法(带括号或不带括号的方法名+参数),而不是直接写符号。
另外补充一点:如果你的case分支里只用puts输出字符串,那方法会返回nil(因为puts的返回值是nil),但你说返回的是:identify_class,所以这个情况可能性低,但也可以留意下——如果想让方法返回字符串,不要只在分支里用puts,要让分支直接返回字符串(比如直接写字符串,或者用return明确返回)。
举个正确的示例参考:
def identify_class(str) case str when "student" "This is a Student class" # 这行的字符串会作为case的返回值,也就是方法的返回值 when "teacher" "This is a Teacher class" else "Unknown class" # 别忘了处理默认情况哦 end end # 调用方法并输出结果 puts identify_class("student")
这样调用后,控制台会输出预期的字符串,方法本身也会返回该字符串。
内容的提问来源于stack exchange,提问作者Kemilio
相关产品推荐
相关产品推荐

