Changing text based on the final letter of user name using regular expression

后端 未结 2 1827

I am looking to change the ending of the user name based on the use case (in the language system will operate, names ends depending on how it is used).

So need to defin

2条回答
  •  难免孤独
    2021-01-21 06:10

    You can use String#gsub with block. Docs say:

    In the block form, the current match string is passed in as a parameter, and variables such as $1, $2, $`, $&, and $' will be set appropriately. The value returned by the block will be substituted for the match on each call.

    So you can use a regex with concatenation of all substrings to be replaced and then replace it in the block, e.g. using a hash that maps matches to replacements.

    Full example:

    replacements = {'e'=>'ai', 'us'=>'mi', 'i' => 'as'}
    ['surname', 'surnamus', 'surnami'].map do |s| 
      s.gsub(/(e|us|i)$/){|p| replacements[p] }
    end
    

提交回复
热议问题