Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional regex string substitution in Ruby (on Rails)

I have a string that can either be something like

create

or

create by

depending on the verb, etc. In Ruby (on Rails) to get the past tense

string.sub(/e?$/, "ed") 

or

string.sub(/ by?$/, "ed by") 

works, but is there any way to combine the two? With some type of conditional statement or similar.

like image 287
jiku Avatar asked Jan 03 '14 19:01

jiku


2 Answers

Using word boundary (\b):

'create by'.sub(/e\b/, 'ed')
# => "created by"
'create'.sub(/e\b/, 'ed')
# => "created"
like image 118
falsetru Avatar answered Nov 04 '22 20:11

falsetru


Why not?

2.1.0-preview2 :046 > 'create'.sub('create', 'created')
 => "created"
2.1.0-preview2 :047 > 'create by'.sub('create', 'created')
 => "created by"

And no regexps... )

like image 26
Danil Speransky Avatar answered Nov 04 '22 20:11

Danil Speransky