From: sto.mar@... Date: 2013-04-20T18:41:14+09:00 Subject: Re: Input: sentence Modify: words Output: modified sentence Am 20.04.2013 04:46, schrieb Philip Parker: > Thank you all! You are helping me to understand more complicated > expressions. I actually did get it to work with my simple logic: The below code doesn't look "rubyish" at all. A few suggestions: - use descriptive variable names, not `s', `p', ... (then you can get rid of most of the comments) - do not use `while' loop, use `each' !!! - do not use global variables > #Limitations: assumes no internal punctuation (i.e. hyphens, commas, > periods on abbreviations, quotes, apostrophes, etc.) > #Known outputs: will return unmodified alphanumeric instances, for > example "3rd". > > s="There are 12 chickens for 2 roosters." > #get punctuation from end of sentence > p=s[-1].chr chr is not needed, s[-1] already is a string with length 1 > #create array without end punctuation > anop = s.split(p) s[0...-1], split is not needed here > #create the sentence no end punctuation > snop = anop.join not needed when you don't split > #Make initial word array equal to working output array > array = output = snop.split(' ') why 2 arrays? you could just append words to an initially empty output array > #iterate through all words in the array. If digits then return > unchanged, otherwise abbreviate as requested. > $i = 0 > $num = a.length > while $i < $num do > if a[$i].match(/\d/) > then output[$i]=a[$i] > else output[$i]=a[$i][0].chr + (a[$i].length-2).to_s + a[$i][-1].chr > end > $i +=1 > end 1. iteration: use each and append to an initially empty output array 2. if: `then' is not needed; bad indentation: if ... output... else output... end > #add punctuation back to last word > output[-1]<

#rejoin output array as abbreviated sentence > os = output.join(' ') > #output abbreviated sentence > puts os --