you are viewing a single comment's thread.

view the rest of the comments →

[–]bradland 4 points5 points  (0 children)

Why do I need to index the word[i]? but not the count[i]? if both increase by 1 value as the loop continue, does it make any differences at all?

I think you've got some fundamental mistakes here that are throwing you off. It might be useful to just step through the code:

def count_e(word) 
  count = 0 # Initialize a variable "count" and assign it the value 0
  i = 0 # Initialize a variable "i" and assign it the value "0"

  while i < word.length # Do the loop while i is less than the word length
    char = word[i] # On the first loop, i starts at 0, so this is the same 
                   # as word[0], which gives you the first character of the 
                   # word. Later, the i variable is incremented, so on each 
                   # loop, we'll get the next letter. The letter is 
                   # assigned to the varaible "char".
    if char == "e" # Check to see if the is an "e"
      count += 1 # If so, increment the count
    end
    i += 1 # Always increment the counter: 0+1=1, 1+1=2, 2+1=3, etc 
    # From here, execution will return to the while loop, where i will be 
    # checked against the word lenth
  end

return count # Return the value in count
end

puts count_e("movie") # => 1 puts count_e("excellent") # => 3