Reputation: 87
In my system, users will register their names. In the natural language the system is used with, names end differently depending its use, such as:
"name surname"
"namai surnamai"
Due to this, I need to change the ending of @provider_user.name
in some places; if it ends with e
, replace e
with ai
.
My HTML slim code is:
= render partial: 'services/partials/messages/original_message', locals: { header: t('html.text.consultation_with.for_provider', name: @provider_user.name)
It takes text from a yml file and uses @provider_user.name
.
Any suggestions to work this around?
Upvotes: 0
Views: 112
Reputation: 1005
It's really easy, that's why I love Ruby...
class String
def replace_ends(replace, with)
end_array = self.split " "
end_array.map! do |var|
break unless var.end_with? replace
var.chomp(" ").chomp(replace) + with
end
return end_array.join " "
end
end
Upvotes: 1
Reputation: 465
Try this, simple single line code
@provider_user.name.split.map {|w| (w.end_with?('e') ? (w.chomp(w[w.length - 1]) + 'ai') : w) }.join(" ")
I am sure, it will convert "name surname"
to "namai surnamai"
.
In additional cases...
@provider_user.name.split.map {|w| (w.end_with?('e') ? (w.chomp(w[w.length - 1]) + 'ai') : (w.end_with?('us') ? (w.chomp(w[w.length - 1]) + 'mi') : (w.end_with?('i') ? (w.chomp(w[w.length - 1]) + 'as') : w))) }.join(" ")
Upvotes: 1
Reputation: 102250
"name surname".gsub(/e\b/, 'ai') # "namai surnamai"
.gsub
uses a regular expression to search and replace in a string. Its the greedy version of .sub
meaning that it will replace all occurrences.
\b
matches any word boundry.
Upvotes: 3