Changing text based on the final letter of user name

落花浮王杯 提交于 2019-12-11 17:15:23

问题


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:

  • who: "name surname"
  • with who: "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?


回答1:


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(" ")



回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/53595868/changing-text-based-on-the-final-letter-of-user-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!