简体   繁体   中英

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.

Using word boundary ( \\b ):

'create by'.sub(/e\b/, 'ed')
# => "created by"
'create'.sub(/e\b/, 'ed')
# => "created"

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... )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM