Ruby Regexp using gsub is there an equivalent to self keyword?
arrays, regex, ruby, self, string
Solution
`String#gsub` accepts an optional block. The return value of the block is used as a replacement string.
str.gsub(/[a-z]/) { |x| x.next }
# => "bcd123"
Shorter version using `&:next` syntax:
str.gsub(/[a-z]/, &:next)
# => "bcd123"
Problem
For example say I wanted to take a string and add 1 value to each a-z character. I am looking for something with a similar syntax: ``` str = 'abc123' str.gsub(/[a-z]/, self.next!) ``` Giving an output of: bcd123 I know I could use some code like: ``` irb(main):075:0> 'abc123'.split('').map{|x| if x =~ /[a-z]/ then x.next! else x = x end }.join => "bcd123" ``` However, this seems to be pretty sloppy and not very efficient. I would figure there is a much neater way to accomplish the same feat. Thanks in advance.