Sakshi Jain Sakshi Jain - 6 months ago 11
Ruby Question

Find the next character in a string

Here is a string,

test = "IXIVDL"


How to find which character comes right after "I" in the string?
And whether it is only "X" or "V" or any other?

For eg.

"IDXCN"
is an invalid string because
"I"
id followed by
"D"


"IXD"
is a valid string because
"I"
is followed by
"X"


"IVIX"
is a valid string because
"I"
is followed by
"V"
or
"X"


"DIDIX"
is invalid string because
"I"
is followed by
"D"


"DXI"
is valid

Answer

Check how regular expressions work here: Class: Regexp

This should solve your doubt, notice how the index of the valid substring is returned when it exists:

'IXIVDL' =~ /I[XV]/    # returns 0
'IDXCN'  =~ /I[XV]/    # returns nil
'IXD'    =~ /I[XV]/    # returns 0
'IVIX'   =~ /I[XV]/    # returns 2

If you need to know whether every I is immediately followed by either an X or a V you can use instead:

'DID­IX' =~ /I[^X­V]/

which returns nil for valid strings (notice it accepts I at the end of the string).

Comments