Forum: Ruby on Rails Replace the first word of a string

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.
C65fbc91799a72e3363a8031ea0c41e5?d=identicon&s=25 Robert Scott (rscott239)
on 2009-04-23 10:22
Does anybody have a good starting point for how to read the first word
of a string and then, based on several defined pairs, swap it?

I've been considering using something like

@split = @message.split('-')
if @split[0] == "word"
...
elsif @split[0] == "otherword"
...
end

Even if this is the best way to do it, I'm not sure how to replace the
word or patch the string back up for display. :/
41cc2c53544016a86472343ab3fdc0ff?d=identicon&s=25 Simon Macneall (Guest)
on 2009-04-23 10:37
(Received via mailing list)
How about something like

words = {}
words['word'] = 'newword'
words['otherword'] = 'newotherword'

outmessage = message
splits = message.split(' ')
if (words[splits[0]])
  splits[0] = words[splits[0]]
  outmessage = splits.join(' ')
end

obviously it can be cleaned up a fair bit, but the hash will save having
a god awful if or switch statement

Simon
29ebf90af6107d2eb39b587c7972639c?d=identicon&s=25 Mukund (Guest)
on 2009-04-23 11:16
(Received via mailing list)
how about this?

lookup = { "word"=>"newword",..}
first_word = @message[0...@message.index(" ")]
first_word = lookup[first_word]


On Apr 23, 1:22 pm, Robert Scott <rails-mailing-l...@andreas-s.net>
This topic is locked and can not be replied to.