I created a method to count a substring 'e'
in a string passed as an argument. If there isn't a substring 'e'
in the string, it should return "There is no \"e\"."
I am trying to achieve this:
'e'
is in a string."e"
, return "There is no "e"."
nil
, return nil
.This is my code:
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")
It skips the if
statement and it still uses the method count
. Why is this?
To achieve what you want you could move your string.count
to the else
statement in your if
, because actually you're making your method return the quantity of e
passed in the count
method over your string, but what happens inside the if
isn't being used:
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('') # => ""
And also your validations must be in order, first check nil
values, then empty values, and then the rest, if you don't then you'll get some undefined method ___ for nil:NilClass
errors.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments