根据一些规则替换Ruby字符串中的字符
在Ruby中,我有一串相同的字符 - 假设它们都是感叹号,如!!!!
。如果与该索引相对应的整数符合某些标准,我想用'*'替换某些索引处的字符。根据一些规则替换Ruby字符串中的字符
例如,假设我想要替换索引为偶数且大于3的所有字符。在字符串!!!!!!!!
(8个字符长)中,结果为!!!!*!*!
(索引4和6已被替换) 。
什么是最简单的方法来做到这一点?
这里是一个版本,将修改现有的字符串到位:
str = '!!!!!!!!'
str.split('').each_with_index do |ch, index|
str[index] = '*' if index % 2 == 0 and index > 3
end
我是新来的红宝石,但我想我会搏一搏。 mikej的回答要好得多。
str = '!!!!!!!!'
index = 0
str.each_char { |char|
if (3 < index) && (index % 2 == 0) then
str[index] = '*'
end
index = index + 1
}
puts str
编辑
这里是一个小更好的解决方案结合了一些其他(已测试)。
str = '!!!!!!!!'
str.split('').each_with_index do |char, index| 3 < index and index % 2 == 0 ? str[index] = '*' : str[index] = char end
puts str
我也是Ruby新手,但enum_with_index函数引起了我的注意。
第二次更新:这就是我的意思。此代码已经过测试。
"!!!!!!!".split('').enum_with_index.map{|c,i|(i%2==0 and i>3)?'*':c}.inject(""){|z,c|z+c}
可能是最紧凑,你可以得到(比其他解决方案更确切),但谁知道?
s="!!!!!!!!"
4.step(s.length-1, 2) {|i| s[i]="*"}
puts s
我还猜测它可能是最有效的,与其他解决方案相比。
对于那些你们谁和我一样,痴迷与链统计员的无限可能给我们:
str = '!!!!!!!!'
res = '!!!!*!*!'
str.replace(str.chars.with_index.inject('') { |s, (c, i)|
next s << c unless i%2 == 0 && i > 3
s << '*'
})
require 'test/unit'
class TestStringReplacement < Test::Unit::TestCase
def test_that_it_replaces_chars_at_even_indices_greater_than_3_with_asterisk
assert_equal res, str
end
end
看起来很酷,而且可能比我的效果更好:) – 2009-11-19 16:11:03
我爱你,包括这个例子的测试! – JohnMetta 2010-06-11 18:18:13
怎么样的正则表达式?
s="!!!!!!!!"
puts s[0..3]+s[4..s.size].gsub(/!{2}/,"*!")
我得到测试时返回的原始字符串。不确定如何使用注入(我正在研究它)。 – 2009-11-19 14:44:47
不,如果你得到原始字符串,那么它不起作用。我不想浪费你的时间。几个小时后,我可以测试这个并修复它。 – 2009-11-19 15:40:55
完成:我的最大努力,现在纠正和测试。 – 2009-11-19 19:20:32