gpt4 book ai didi

ruby - Rubocop 进攻 : Use the return of the conditional for variable assignment and comparison

转载 作者:数据小太阳 更新时间:2023-10-29 08:19:29 27 4
gpt4 key购买 nike

我的 Rubocop 攻击告诉我我需要“使用条件的返回来进行变量赋值和比较”

虽然我尝试修复它,但它又冒犯了我“方法行太长”。

我尝试重构为另一种方法,但我的代码出错了。

如何缩短或重构此代码?

HSH = { 'a' => 'z', 'b' => 'y', 'c' => 'x', 'd' => 'w', 'e' => 'v', \
'f' => 'u', 'g' => 't', 'h' => 's', \
'i' => 'r', 'j' => 'q', 'k' => 'p', 'l' => 'o', 'm' => 'n' }.freeze


def encoder(str)
encoded_string = ''
str.chars.each do |char|
encoded_string = if HSH.key?(char) then encoded_string += HSH[char]
elsif HSH.invert.key?(char) then encoded_string += HSH.invert[char]
else encoded_string += char
end
end
encoded_string
end

当我运行测试套件时,一切正常。

但是 rubocop offense 给我的方法行太长了。

最佳答案

无哈希:

ALPHABET = ("a".."z").to_a.join

def encoder(str)
str.tr(ALPHABET, ALPHABET.reverse)
end

关于ruby - Rubocop 进攻 : Use the return of the conditional for variable assignment and comparison,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55792811/

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