简体   繁体   中英

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! 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 . 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.

To do it inplace you could use 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 is a character and i is an index.

if name=huzefa and you want to replace 'a' with its index..

name.split(//).map.with_index{|x,y| (x=='a')? y : x}.join

to result in #> "huzef5"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM