gpt4 book ai didi

ruby - 根据某种规则替换 Ruby 字符串中的字符

转载 作者:太空宇宙 更新时间:2023-11-03 17:19:25 25 4
gpt4 key购买 nike

在 Ruby 中,我有一串相同的字符——假设它们都是感叹号,如 !!!!。如果对应于该索引的整数满足某些条件,我想用'*'替换某些索引处的字符。

例如,假设我要替换所有索引为偶数且大于 3 的字符。在字符串 !!!!!!!!(8 个字符长)中,结果为 !!!!*!*!(索引 4 和 6 已被替换)。

执行此操作最紧凑的方法是什么?

最佳答案

这是一个将修改现有字符串的版本:

str = '!!!!!!!!'
str.split('').each_with_index do |ch, index|
str[index] = '*' if index % 2 == 0 and index > 3
end

关于ruby - 根据某种规则替换 Ruby 字符串中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1763388/

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