Forum: Ruby how to substitute group of words in a line with another text

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Muralidharan R. (Guest)
on 2009-04-03 22:11
I am trying to create a routine which will convert text to SMS lingo
format. For example a sentence might contain "This should be done as
soon as possible". I have created a HASH which stores "ASAP" => "as soon
as possible".
My routine should parse the message and subsitute with "ASAP" and return
a string "This should be done ASAP".

def SMSdeflater(message)

    @smsdictionary.each_pair do
      |key, value|
      tmpvalue = value.chomp.downcase
      msg=message.chomp.downcase
      puts "looking for <#{tmpvalue}> in <#{msg}>"
      newmsg=msg.gsub(tmpvalue,key)
      puts newmsg
 end

the above mentioned code is not working, any help is appreciated

thanks,
murali
Robert K. (Guest)
on 2009-04-03 22:41
(Received via mailing list)
On 03.04.2009 20:10, Muralidharan Regupathy wrote:
>       |key, value|
>       tmpvalue = value.chomp.downcase
>       msg=message.chomp.downcase
>       puts "looking for <#{tmpvalue}> in <#{msg}>"
>       newmsg=msg.gsub(tmpvalue,key)
>       puts newmsg
>  end
>
> the above mentioned code is not working, any help is appreciated

If there are not many phrases you can use Regexp.union:

msg.gsub Regexp.union(@smsdictionary.keys) do |match|
   @smsdictionary[match]
end

Kind regards

  robert
Muralidharan R. (Guest)
on 2009-04-03 23:06
Robert K. wrote:
> On 03.04.2009 20:10, Muralidharan Regupathy wrote:
>>       |key, value|
>>       tmpvalue = value.chomp.downcase
>>       msg=message.chomp.downcase
>>       puts "looking for <#{tmpvalue}> in <#{msg}>"
>>       newmsg=msg.gsub(tmpvalue,key)
>>       puts newmsg
>>  end
>>
>> the above mentioned code is not working, any help is appreciated
>
> If there are not many phrases you can use Regexp.union:
>
> msg.gsub Regexp.union(@smsdictionary.keys) do |match|
>    @smsdictionary[match]
> end
>
> Kind regards
>
>   robert

Thanks Robert
However i tried otherway and it seems to work fine. I know my solution
is not a clean one but it works for my learning.
def SMSdeflater(message)
     msg=message.chomp.downcase
    @smsdictionary.each_pair do
      |key, value|
      tmpvalue = value.chomp.downcase
      msg=msg.sub(tmpvalue,key)
      puts msg
    end
end
This topic is locked and can not be replied to.