1

Question

I saw this same question at Replace string with values from two arrays and thought I'd ask and respond to it in Ruby code (as the question was in Javascript)

I have a string for example:

str = 'This is a text that needs to change'

and two arrays:

arr0 = %w[a e i o u]
arr1 = %w[1 2 3 4 5]

I want to replace characters in str and arr0 with their corresponding arr1 values. The output should be:

'Th3s 3s 1 t2xt th1t n22ds to ch1ng2'

Since I plan to use this with large chunks of data, I expect the solution to be efficient.

Solution

str.gsub(Regexp.new(/[#{arr0.join('')}]/), Hash[[arr0, arr1].transpose])
=> "Th3s 3s 1 t2xt th1t n22ds t4 ch1ng2"

Feel free to share your solution to this problem =)

Community
  • 1
  • 1
Abdo
  • 13,549
  • 10
  • 79
  • 98

3 Answers3

4
str.tr arr0.join, arr1.join
# => Th3s 3s 1 t2xt th1t n22ds t4 ch1ng2
Matt
  • 20,108
  • 1
  • 57
  • 70
  • Hi @Matt! i think it is good in his case. But in this case: `text = "[A] and [B]"`, `original = ["[A]", "[B]", "[C]", "[D]", "[Aa]"]`, `replacements = ["[B]", "[C]", "[D]", "[E]", "[Bb]"]` How can you replace the `text` to `"[B] and [C]"` – Hieu Le Mar 25 '15 at 05:56
  • @Ronan That requires pattern matching and substitution, instead of the simple `tr` method. Best to ask that as a separate question. – Matt Mar 25 '15 at 06:04
  • Thank you! i will ask as a separate question! – Hieu Le Mar 25 '15 at 07:28
1

I would do it either as @Matt has, or like this:

str = 'This is a text that needs to change'
h = {"a"=>"1", "e"=>"2", "i"=>"3", "o"=>"4", "u"=>"5"}

str.gsub /[#{h.keys.join}]/, h
  #  => "Th3s 3s 1 t2xt th1t n22ds t4 ch1ng2" 
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
0

if the indexes of the vowel remains unchanged:

str = 'This is a text that needs to change'
%w[a e i o u].each_with_index { |x,i| str.gsub!(x,(i+1).to_s)}
str # => "Th3s 3s 1 t2xt th1t n22ds t4 ch1ng2"
bjhaid
  • 9,592
  • 2
  • 37
  • 47