Reputation: 13378
Using Ruby. Fiddle in http://rubyfiddle.com/riddles/c9c29
# code
term = "123 code ruby"
f_term = term.gsub(/\s/, "% %").insert(0, "%").insert(-1, "%")
puts f_term
# output
%123% %code% %ruby%
How would you refactor my f_term
?
Upvotes: 0
Views: 53
Reputation: 84343
Assuming that all you really want to do is surround each word with percent signs, you don't really need to do all those gymnastics with your string. Just use String#gsub and replace your word boundaries. For example:
term = '123 code ruby'
f_term = term.gsub /\b/, '%'
# => "%123% %code% %ruby%"
Upvotes: 2
Reputation: 14222
term.gsub(/\b/, '%') # %123% %code% %ruby%
Since this uses word boundaries, the behavior is slightly different from yours. The /\b/
method will return %cats%
for the input cats
where yours would have produced %% %% %cats% %% %%
Upvotes: 3