gpt4 book ai didi

ruby - 调用方法不返回字符串

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

我创建了一个方法来计算作为参数传递的字符串中的子字符串 'e'。如果字符串中没有子字符串 'e',它应该返回 "There is no\"e\"." 我正在努力实现这一点:

  • 'e' 在一个字符串中出现了多少次。
  • 如果给定的字符串不包含任何"e",返回"There is no "e"."
  • 如果给定的字符串为空,则返回空字符串。
  • 如果给定的字符串是nil,返回nil

这是我的代码:

def find_e(s)
if !s.include?("e")
"There is no \"e\"."
elsif s.empty?
""
else s.nil?
nil
end
s.count("e").to_s
end

find_e("Bnjamin")

它跳过了 if 语句,它仍然使用方法 count。这是为什么?

最佳答案

为了实现你想要的,你可以将你的 string.count 移动到你的 if 中的 else 语句,因为实际上你正在您的方法返回在 count 方法中通过您的字符串传递的 e 的数量,但是 if 内部发生的情况没有被使用:

def find_e(s)
if s.nil?
nil
elsif s.empty?
''
elsif !s.include?("e")
"There is no \"e\"."
else
s.count("e").to_s
end
end

p find_e("Bnjamin") # => "There is no \"e\"."
p find_e("Benjamin") # => "1"
p find_e(nil) # => nil
p find_e('') # => ""

而且你的验证必须按顺序进行,首先检查 nil 值,然后是空值,然后是其余的,如果你不这样做,那么你会得到一些 undefined 方法 ___对于 nil:NilClass 错误。

关于ruby - 调用方法不返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45176365/

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