simple regex -- replace underscore with a space

40,028

Solution 1

Whoops, I actually had it working--just forgot to update the variable name :P

I was using this:

@id = params[:id]
@title = @id.gsub("_", " ")

Solution 2

str.gsub!(/_/, ' ')

gsub stands for 'global substitution', and the exclamation means it'll change the string itself rather than just return the substituted string.

You can also do it without regexes using String#tr!:

str.tr!('_', ' ')

Solution 3

On rails you can use the simplier .humanize and ruby's .downcase method but be careful as it also strips any final '_id' string (in most cases this is just what you need, even the capitalized first letter)

'text_string_id'.humanize.downcase
 => "text string" 
Share:
40,028

Related videos on Youtube

mportiz08
Author by

mportiz08

Updated on July 09, 2022

Comments

  • mportiz08
    mportiz08 almost 2 years

    Hey, I'm writing my first Rails app, and I'm trying to replace the underscores form an incoming id name with spaces, like this:

    before: test_string

    after: test string

    How can I do this? Sorry if this is a bit of a dumb question, I'm not very familiar with regular expressions...

  • draw
    draw almost 13 years
    str.tr!('_', ' ') will return nil if str doesn't include any _
  • Christoph
    Christoph over 6 years
    Alternatively, 'text_string_id'.humanize(capitalize: false) will allow you to skip the extra downcase transformation.
  • tagaism
    tagaism over 4 years
    Not only in rails. split() and join() are standard ruby methods.