Ruby中如何指定单个方法参数值,其余用默认值?实例排查
在Ruby中为特定方法参数赋值(其余用默认值)及问题排查
通用解决方法
要只为特定方法参数设置值、其余保留默认值,Ruby 2.0及以上版本最推荐用关键字参数——这种方式不用纠结参数顺序,直接指定参数名即可:
- 定义方法时给参数加上冒号,同时设置默认值:
def 方法名(必传参数, 参数1: 默认值1, 参数2: 默认值2) # 方法逻辑 end - 调用时只需传入必传参数和要修改的参数:
方法名(必传值, 参数2: 新值)
如果坚持用传统位置参数,就必须按参数顺序传递,跳过的参数要显式传入它的默认值(比如参数顺序是a, b=1, c=2,要改c就得传(a_val, 1, new_c_val)),但这种方式参数多了容易出错,不推荐。
你的代码错误原因及修复
错误分析
你写的super_string2 = SuperString.new("world", parent_class = "None")里,parent_class = "None"是一个局部变量赋值操作,不是指定方法参数。这个赋值的结果会被当成第二个位置参数传给id_num,而第三个参数parent_class还是用默认值"String",所以输出才是String。
修复方案
方案1:改用关键字参数(推荐)
把方法定义改成关键字参数形式,就能直接指定要修改的参数:
class SuperString < String def initialize(str, id_num: 0, parent_class: "String") super(str) @id_num = id_num @str_length = str.length @creator = "Me" @parent_class = parent_class end attr_accessor :id_num, :str_length, :creator, :parent_class end super_string1 = SuperString.new("world", id_num: 0, parent_class: "None") puts super_string1.parent_class # 输出 None super_string2 = SuperString.new("world", parent_class: "None") puts super_string2.parent_class # 输出 None
方案2:按位置参数规则传值
如果不想修改方法定义,就得按位置参数的规则,显式传入前一个参数的默认值:
super_string2 = SuperString.new("world", 0, "None")
内容的提问来源于stack exchange,提问作者Brijesh
相关产品推荐
相关产品推荐

