2

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 =)

3 Answers 3

5
str.tr arr0.join, arr1.join
# => Th3s 3s 1 t2xt th1t n22ds t4 ch1ng2
Sign up to request clarification or add additional context in comments.

2 Comments

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]"
@Ronan That requires pattern matching and substitution, instead of the simple tr method. Best to ask that as a separate question.
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" 

Comments

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.