gpt4 book ai didi

ruby - 如何让gsub方法只改变一次

转载 作者:行者123 更新时间:2023-12-03 07:52:26 25 4
gpt4 key购买 nike

我没有很好地表达标题,因为我无法解释它,但如果我有的话,可以说我有这样的东西

puts ("red, blue").gsub("red", "blue").gsub("blue", "red")

我想让“红,蓝”变成“蓝,红”,这是彼此相反的,但是因为“红”变成“蓝”,然后“蓝”变成“红”马上又回来了,它只是不起作用。

我尝试了另一种方法,我想让“快乐”一词的所有实例都被“悲伤”替换,反之亦然

最佳答案

您可以以散列形式提供替换。匹配模式的键(必须是字符串),值是替换:

>> "red, blue, blue, green".gsub(/red|blue/, {"red" => "blue", "blue" => "red"})
=> "blue, red, red, green"
>> "happy happy sad".gsub(/sad|happy/, {"sad" => "happy", "happy" => "sad"})
=> "sad sad happy"

对于更复杂的操作:

"happy happy sad red blue".gsub(/\w+/) do |m|
case m
when "happy" then "red"
when "sad" then "blue"
when "red" then "sad"
when "blue" then "happy"
end
end
=> "red red blue sad happy"

https://rubyapi.org/3.3/o/string#class-String-label-Substitution+Methods

关于ruby - 如何让gsub方法只改变一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76844273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com