Search code examples
ruby

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.


Solution

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