I'm New - Help with scanning a string

If anyone can help me understand a little better i would greatly appreciate it.

I’m basically trying to scan an input from a user against a variable to see if there is any matching characters and if there are any matching characters i want to store them and also print them.

I just can’t get my head around it (sorry i’m literally 4 days into ruby)

Example:
str1 = “abcdefg”
str2 = “”

puts = “enter word”

user enters - “acg”

str2 = gets.chomp

str2 =“acg”

matching_letters = (str1.chars & str2.chars)

#matching_letters = “a,c,g”

now i want to scan ‘matching_letters’(a,c,g) against str1 and i want to show the user the letters they have matched and also the position of str1 they have matched in. But i dont know how to do it??

for example the letters would matching_letters (a,c,g) would match positions [0],[2],[7]

But how do i scan that and make sure that stay in the matched postion??

Thank you so much for taking the time to help me. I really appreciate it

First, make sure that your strings are converted to arrays of characters. Then use map and index to get what you want (by the way, the expected result in your example is [0,2,6], not [0,2,7]; g is at position 6). So:

str1 = 'abcdefg'.chars
str2 = gets.chomp.chars # user enters 'acg'
str2.map { |c| str1.index(c) } # [0, 2, 6]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs