Nelly-Johan Nelly-Johan - 2 months ago 8
Ruby Question

How to replace letters in a string with a hash value

I want to extract some letters from a word and replace the letters by their chemical symbol.

This works, but it's TOOOO long. I am sure there is a way to make it shorter:

puts "Enter your name"
name = gets.chomp

if name.include? 'br'
name.gsub!('br', 'Br')
end
if name.include? 'ba'
name.gsub!('ba', 'Ba')
end
if name.include? 'cr'
name.gsub!('cr', 'Cr')
end

if name.include? 'ac'
name.gsub!('ac', 'Ac')
end

if name.include? 'al'
name.gsub!('al', 'Al')
end

if name.include? 'am'
name.gsub!('am', 'Am')
end


I am trying to do this way but it doesn't work. What is wrong?

puts "Enter your name"
name = gets.chomp

symbols = {
:ac => "Ac",
:al => "Al",
:am => "Al",
:br => "Br",
:ba => "Ba",
:cr => "Cr"
}


if name.include? symbols
symbols.each{ |key, value| name.gsub!(key, value) }
end

puts name


I get the following error:

breakingbad.rb:15:in `include?': no implicit conversion of Hash into String (TypeError)
from breakingbad.rb:15:in `<main>'

Answer

Use String as Hash key. String#gsub also accepts a Hash as second argument.

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

symbols = {
  'ac' => "Ac",
  'al' => "Al",
  'am' => "Al",
  'br' => "Br",
  'ba' => "Ba",
  'cr' => "Cr"
}
puts "Enter your name"
name = gets.chomp
name.gsub!(/#{symbols.keys.join('|')}/, symbols)
puts name
Comments