I will output it for Ruby learning. This time, I will introduce how to replace characters using "gsub method" and "sub method".
You can replace all the matched parts by using the gsub method.
n =gets ← (this time tests on gets-I typed test)
m = n.gsub("test","hoge")
=> hoge-hoge(test-test is hoge-Replaced by hoge)
By using the sub method, you can replace only the first matching part.
n =gets ← (this time tests on gets-I typed test)
m = n.sub("test","hoge")
=> hoge-test(test-test is hoge-Replaced by test)
s =gets ← (Enter PAIZA in gets this time)
n = s.gsub(/A|E|G|I|O|S|Z/,"A" => 4,"E" => 3,"G"=>6,"I"=>1,"O"=>0,"S"=>5,"Z"=>2)
>> P4124
The part corresponding to the regular expression matched by the first argument is replaced with the second argument
If you don't use regular expressions
String.gsub(置換したいString, 置換後のString)
>>Character string after replacement
When using regular expressions
String.gsub(/Regular expressions/, Regular expressionsに該当した箇所を置換した後のString)
>>Character string after replacing the part corresponding to the regular expression
Recommended Posts