def year=(new_year): Defines a setter method that allows you to set the value of @year with car.year = 2022.
def year(new_year): Defines a regular instance method that needs to be called with car.year(2022) and does not assign the value to @year unless you explicitly do so inside the method.
sentences = [
"the dog, the cat, the zebra, the giraffe",
"the, the code, and the developer",
"then the- their"
]
sentence = sentences.sample
pp sentence
# write your program below
the_count = sentence.scan(/\bthe\b/).count
pp "'the' appeared #{the_count} times"
The issue with the code is how the .count method is being used. The .count method in Ruby, when used on strings, doesn’t count occurrences of whole words but instead counts individual characters that match any in the set of characters provided as an argument. In this case, new_sentence.count("the") is counting each occurrence of ‘t’, ‘h’, and ‘e’ individually, not the word ‘the’.
To count occurrences of the whole word ‘the’, you would need to use a different approach, such as using the .scan method with a regular expression that matches the word ‘the’ followed by a boundary to ensure it’s a whole word:
Here, /\bthe\b/ is a regular expression where \b denotes a word boundary, ensuring that only the whole word ‘the’ is matched, not ‘the’ within other words like ‘then’ or ‘their’. The .scan method returns an array of all matches, and calling .count on that array gives you the number of times the whole word ‘the’ appeared in the sentence.
Top comments (0)