Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMarc Burt
9,828 PointsNeed a bit of .gsub code explained
Here is some code:
def to_param
"#{id}-#{title.gsub(/[^a-z1-9]+/i, '-')}"
end
I know that this appends the content of 'title' to the URL of my routes after the id (I've left the id in since it prevents a lot of other problems and I don't mind it for this project).
The gsub method substitutes non alphanumeric characters with a dash to make them URL friendly, but I'm not sure how that code is written..
I can't find good documentation of it but I think either the ^ before the a the + or the i probably translates to everything except the listed characters. Does anyone know which and what the other characters do?
1 Answer
Naomi Freeman
Treehouse Guest TeacherThe stuff after .gsub is regex (regular expressions):
This is also an excellent resource if you're willing to work through it: http://www.regular-expressions.info/tutorial.html
This one helped a friend of mine through an interview: http://regexone.com/
Does the code you posted work?
Marc Burt
9,828 PointsMarc Burt
9,828 PointsFantastic, thank you.
So the ^ means anything except those characters, the + means include multiples and the i means case insensitive.
Yes the code works perfectly.