gpt4 book ai didi

ruby - 无法使 setter 方法起作用

转载 作者:太空宇宙 更新时间:2023-11-03 17:43:49 25 4
gpt4 key购买 nike

我有一个设置月份的 setter 方法。它需要返回一个字符串'01'-'12'。我希望 ti 能够获取数字和文本(3 个 didgit 月和完整月)。我正在通过输入 Aug 来测试它,但无法让 ti 工作。它将 @month 设置为与输入(Aug)相同。

代码是

def month=(month)
# this can take a number or string, either with 3 char month or full month
# it returns a 2 char string, left padded with 0s

if !month.numeric?
case month.upcase[0,3]
when 'JAN'
month = '01'
when 'FEB'
month = '02'
when 'MAR'
month = '03'
when 'APR'
month = '04'
when 'MAY'
month = '05'
when 'JUN'
month = '06'
when 'JUL'
month = '07'
when 'AUG'
month = '08'
when 'SEP'
month = '09'
when 'OCT'
month = '10'
when 'NOV'
month = '11'
when 'DEC'
month = '12'
else
month = '00'
end
end if
@month=month.rjust( 2, '0' )
end

我用

调用它
event.month = "Aug"
p event.month

现在这里是真正怪异的部分。如果我添加 p 行

            end if
p month
@month=month.rjust( 2, '0' )
end

它打印“Aug”,但该方法有效,“p event.month”在调用后立即返回“08”

知道我哪里做错了吗?

最佳答案

end if 应该只是 end

尾随 if 的存在意味着“除非后面的内容为真,否则不要运行此 case 语句”,因此您的 case 语句仅在您已经设置了 @month 后才会被评估 实例变量。

相当于是

if @month=m.rjust(2, '0')
if !month.numeric?
case month.upcase[0,3]
# when/else statements
end
end
end

所以改成这样:

end
@month=month.rjust(2, '0')

使您的代码工作。

通过将你的 p month 语句添加到调试中,你会导致它首先被评估,所以 case 语句运行(因为 p 有一个真实的返回值) ,后跟 @month 赋值,因此您的代码以正确的顺序运行。

四处游玩,我注意到如果你传递一个数字而不是数字字符串,.rjust 会失败,所以我建议将其更改为:

@month=month.to_s.rjust(2, '0')

通过保存 case 的结果,您的 case 语句可以大大简化,而不是在每个 when 中进行赋值:

m = case month.upcase[0,3]
when 'JAN' then '01'
when 'FEB' then '02'
#...
else '00'
end

或者,您可以这样做,像这样完全消除 case 语句:

def month=(m)
if !m.numeric?
m = Date::ABBR_MONTHNAMES.index(m.capitalize[0,3])
end
@month = m.to_s.rjust(2, '0')
end

关于ruby - 无法使 setter 方法起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45636623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com