0

I want to convert a string based on a hash. For e.g., the string "assistant director" gets converted to "asst dir" when the hash contains "assistant"=>"asst" and "director"=>"dir". I want to do something like:

hash = Hash["executive"=>"exec","assistant"=>"asst","associate"=>"assoc","director"=>"dir"]
str = "assistant director"

hash.each { |k, v| str.gsub!(k, v) }  
# => "asst dir"

Based on this post,

hash.each { |k, v| str.gsub!(k, v) }

should be the answer. But it doesn't return the converted string. And neither does str get changed.

1
  • @BroiSatse final_str doesn't return anything Commented Apr 16, 2014 at 8:43

2 Answers 2

4

Another way of doing this is :-

str.gsub!(/\w+/, hash)

String#gsub!

If the second argument is a Hash, and the matched text is one of its keys, the corresponding value is the replacement string.

Sign up to request clarification or add additional context in comments.

Comments

2

hash.each { |k, v| str.gsub!(k, v) } will return hash.to_a, but it doesn't matter as youa re using gsub! which means that your str is changed in place. Simply do:

hash.each { |k, v| str.gsub!(k, v) }  
str     #=> "asst dir"

3 Comments

@BroiSatse weird, so if str="Director", then hash.each { |k, v| str.downcase.gsub!(k, v) } doesn't work?
@echan00 - It's not weird, gsub! modifies given instance of string in place. downcase on the other hand creates a new string instance, so your gsub! modifies that instance instead of your original string. It should be enough to call str.downcase! once before iteration to fix it. (Note the bang - string will be modified in place again.
thanks! it was the downcase that was what was tripping me up!

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.