[英]Ruby : Replace a character in a String with its index number
I want to replace a character in string when a particular condition is satisfied. 我想在满足特定条件时替换字符串中的字符。 So , I went through the API doc of Ruby and found the
gsub
, gsub!
因此,我浏览了Ruby的API文档,找到了
gsub
, gsub!
etc for similar purpose. 等用于类似目的。 When I implemented that in my program I didn't got any error but din't got the desired output too.
当我在程序中实现该功能时,我没有出现任何错误,但也没有得到所需的输出。
The code which I was trying is this : 我正在尝试的代码是这样的:
name.each_char { |c|
if name[c] == "a"
name.sub( name[c] , c )
puts "matched.... "
end
So , for example , I have a string called huzefa
and want to replace all the letters with its index numbers . 因此,例如,我有一个名为
huzefa
的字符串,并希望将所有字母替换为其索引号。 So , what is the way to do it ? 那么,怎么做呢? Please explain in detail by giving a simple example.
请举一个简单的例子详细解释。
You could pass block to gsub
and do whatever you want when match happend. 您可以将块传递给
gsub
然后在发生匹配时做任何您想做的事情。
To do it inplace you could use gsub!
为此,您可以使用
gsub!
method. 方法。
name = "Amanda"
new_name = name.gsub("a") do |letter|
puts "I've met letter: " + letter
"*"
end
# I've met letter: a
# I've met letter: a
# => "Am*nd*"
If you want to work with indexes, you could do something like this: 如果要使用索引,可以执行以下操作:
new_name = name.chars.map.with_index do |c, i|
if i.odd?
"*"
else
c
end
end.join
#=> => "A*a*d*"
Here c
and i
are passed to the block. 在这里,
c
和i
传递到块。 c
is a character and i
is an index. c
是一个字符,而i
是一个索引。
if name=huzefa
and you want to replace 'a' with its index.. 如果
name=huzefa
并且您要用其索引替换“ a”。
name.split(//).map.with_index{|x,y| (x=='a')? y : x}.join
to result in #> "huzef5"
导致
#> "huzef5"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.