simple regex -- replace underscore with a space
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"
Related videos on Youtube
mportiz08
Updated on July 09, 2022Comments
-
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 almost 13 years
str.tr!('_', ' ')
will return nil ifstr
doesn't include any_
-
Christoph over 6 yearsAlternatively,
'text_string_id'.humanize(capitalize: false)
will allow you to skip the extradowncase
transformation. -
tagaism over 4 yearsNot only in rails. split() and join() are standard ruby methods.