2017-07-18 133 views
2

我創建了一個方法來計算作爲參數傳遞的字符串中的子字符串'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

回答

1

達到你願意,你可以將你的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錯誤。

0

在Ruby中,方法返回它們正文中的最後一條語句。您的方法的最後一條語句始終爲s.count("e").to_s,因爲它不在if語句之內。

+0

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

+1

更精確的將是:*「當未提供顯式返回時,Ruby返回最後一次計算的表達式」*。 – Gerry

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將是最合乎邏輯的行爲。

1

您需要將您的計數方法放在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\"."