5

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.

1

2 Answers 2

6

Using word boundary (\b):

'create by'.sub(/e\b/, 'ed')
# => "created by"
'create'.sub(/e\b/, 'ed')
# => "created"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I forgot to add that the verb can end with anything. I have hacked it to work with sub(/(e?$| )\b/, "ed "). I just don't like the space at the end of the replacement.
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.