+ 6

[Solved]How do I use a variable to contain the search pattern in Ruby using the .gsub() method?

I am trying to isolate integers 0..5 on a word boundary and replace that integer with the corresponding english word. For example, the string '1 11 5 123' becomes 'one 11 five 123' with numbers larger than 5 remaining unchanged. Thank you in advance for your help! https://code.sololearn.com/c5p6ypClE8XY/?ref=app

14th Mar 2020, 7:10 PM
Paul K Sadler
Paul K Sadler - avatar
5 ответов
+ 3
Use "#{var}" to include a variable inside a regexp: num = ["zero", "one", "two", "three", "four", "five"] message = "4 + 2 = 6" (0..5).each do |i| message.gsub!(/\b#{i}\b/, num[i]) end puts message # four + two = 6 You could do the same with just one call to gsub!(): num = ["zero", "one", "two", "three", "four", "five"] message = "4 + 2 = 6" message.gsub!(/\b[0-5]\b/) {|x| num[x.to_i]} puts message # four + two = 6
14th Mar 2020, 8:38 PM
Diego
Diego - avatar
+ 3
Diego thank you that worked well (both ways) I did run into trouble with the single line line solution if I increased the range from 0..5 to 0..20, but the loop worked no mater the range. That really helped, as I had done a lot of searches and was having difficulty nailing down the proper syntax.
14th Mar 2020, 9:11 PM
Paul K Sadler
Paul K Sadler - avatar
+ 3
Diego one more question, can the search pattern be in a variable? string.gsub!(pattern, replacement)
14th Mar 2020, 9:14 PM
Paul K Sadler
Paul K Sadler - avatar
+ 3
Yes, you can. Just assign your regexps to a variable: (0..5).each do |i| pattern = /\b#{i}\b/ message.gsub!(pattern, num[i]) end And yes, my second approach only works for numbers 0-9. For a larger range it's simpler to use a loop.
14th Mar 2020, 9:28 PM
Diego
Diego - avatar
+ 3
Diego Nice, thank you very much 👍
15th Mar 2020, 12:15 AM
Paul K Sadler
Paul K Sadler - avatar