From: Ammar Ali Date: 2011-10-19T22:44:37+09:00 Subject: Re: why doesn't this work? --0015174c3c4c5d1e2e04afa70a3a Content-Type: text/plain; charset=UTF-8 On Wed, Oct 19, 2011 at 3:09 PM, raphael teller wrote: > hey, I am a C programmer that decided to learn Ruby. I got some > exercises to do, but I'm having some trouble in this (silly)one: > > Problem Statement > Given a sentence containing multiple words, find the frequency of a > given word in that sentence. > > i wrote the code below > > def find_frequency(sentence, word) > array = Array.new > array << sentence.split(/ /) > array.delete_if {|i| i.to_s.downcase != word.downcase}.length > end > > but it appears that (i.to_s.downcase) is always different from > (word.downcase), even if the words are the same. can someone explain it > to me, please? > The problem is the way you store the split sentence. The return value of split is an array and you are storing that array into the empty array, so inside the delete_if loop you are dealing with the whole array of words, not individual words. Now calling to_s on an array will return a string that contains all the elements from that array, concatenated. Obviously this string will not match any single word. >> s = "This is a test of this" => "This is a test of this" >> a = s.split(/ /) => ["This", "is", "a", "test", "of", "this"] >> a.to_s => "Thisisatestofthis" By the way, you don't need to call Array.new to create a new empty array. The following is equivalent: my_array = [] Regards, Ammar --0015174c3c4c5d1e2e04afa70a3a--