调用方法不返回字符串

问题描述:

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

+0

您已翻转其他和elsif。 – Casey

+0

抱歉错误的代码,我改变了。 – Benjamints

+0

这仍然是错误的。 – Casey

达到你愿意,你可以将你的string.countelse语句进行if什么,因为其实你让你的方法返回的ecount方法在你的字符串传递的数量,但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 method ___ for nil:NilClass错误。

在Ruby中,方法返回它们正文中的最后一条语句。您的方法的最后一条语句始终为s.count("e").to_s,因为它不在if语句之内。

+0

如果我想要包含count方法,我必须在我的'if'语句中使用它吗? – Benjamints

+1

更精确的将是:*“当未提供显式返回时,Ruby返回最后一次计算的表达式”*。 – Gerry

您可能很难使用您编写的方法。在下一个方法中,您将需要一个新的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将是最合乎逻辑的行为。

您需要将您的计数方法放在if/else语句的分支中,否则将每次最后一次对其进行评估。如果没有明确的return语句,Ruby将返回最后一条语句,因此将该方法放在最后一行的if/else分支之外可以保证它始终处于打开状态。此外,nil可以通过调用#to_s转换为空字符串,这样你就可以通过转换s.to_s,呼吁empty?和返回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一个字符串,你可以把它一行

def find_e(s) 
    s.to_s.count("e").to_s 
end 

如果是我我可能会返回一个整数,它可以在以后转换为字符串。 puts"#{}"将默认为您打电话to_s。然后,您可以在演示文稿逻辑中使用该整数返回值。

def count_e(input) 
    input.to_s.count("e") 
end 

def check_for_e(input) 
    count = count_e(input) 
    count > 0 ? count.to_s : "There's no \"e\"." 
end 

check_for_e("Covfefe") # => "2" 
check_for_e("Bnjamin") # => "There's no \"e\"." 
check_for_e(nil) # => "There's no \"e\"." 
check_for_e("") # => "There's no \"e\"."