调用方法不返回字符串

时间:2017-07-18 20:21:30

标签: ruby

我创建了一个方法来计算作为参数传递的字符串中的子串'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。这是为什么?

4 个答案:

答案 0 :(得分:1)

要实现您的目标,您可以将string.count移至else中的if语句,因为实际上您正在使您的方法返回{{1}的数量在e方法中传递了你的字符串,但count内部发生的事情并未被使用:

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错误。

答案 1 :(得分:1)

您可能很难使用您编写的方法。在下一个方法中,您需要一个新的case语句来测试find_e是否返回nil,一个空字符串,一个带数字或"no e"的字符串。

这种方法会更加一致:

def count_e(string_or_nil)
  count = string_or_nil.to_s.count("e")
  if count == 0
    "There is no \"e\"."
  else
    count
  end
end

puts count_e("Covfefe")
# 2
puts count_e("Bnjamin")
# There is no "e".
puts count_e("")
# There is no "e".
puts count_e(nil)
# There is no "e".

但实际上,如果输入中没有e,那么返回0将是最符合逻辑的行为。

答案 2 :(得分:1)

您需要将count方法放在if/else语句的分支中,否则每次都会对其进行最后评估。如果没有显式的返回语句,Ruby将返回最后一个语句,因此将该方法放在最后一行的if/else分支之外可确保它始终被命中。此外,nil可以通过调用#to_s转换为空字符串,因此您可以通过转换s.to_s,调用empty?并返回{{1}来删除您的某个分支}

s

如果您只是返回def find_e(s) if s.to_s.empty? s elsif !s.include?("e") "There is no \"e\"." else s.count("e").to_s end end ,无论是0,空字符串还是没有nil的字符串,都可以将其设为一行

e

如果是我,我可能会返回一个Integer,后来总是可以转换为String。 def find_e(s) s.to_s.count("e").to_s end puts将隐含地为您调用"#{}"。然后,您可以在表示逻辑中使用该整数返回。

to_s

答案 3 :(得分:0)

在Ruby中,方法返回其体内的最后一个语句。您方法的最后一条语句始终为s.count("e").to_s,因为它位于if语句之外。