On Apr 20, 2013 4:42 AM, <sto.mar / web.de> wrote:
>
> 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]<<p
>> #rejoin output array as abbreviated sentence
>> os = output.join(' ')
>> #output abbreviated sentence
>> puts os
>
>
> --
> <https://github.com/stomar/>
>

since we're sharing, here's mine:

def numify_w(s)
return s if s.nil? || s.empty? || s.length < 3
s.match(/^([[:punct:]]*)([-_'[:alpha:]]+)([[:punct:]]*)$/) do |m|
m[1]+m[2][0]+m[2].length.to_s+m[2][-1]+m[3]
end or s
end

def numify(s)
return s if s.nil? || s.empty?
s.split.map{|m| numify_w m}.join(" ")
end

handles some intraword punctuation