我想从一个单词中提取一些字母,并用它们的化学符号替换字母。
这很有效,但它很长。我确信有一种方法可以缩短它:
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
我试图这样做,但它不起作用。有什么问题?
puts "Enter your name"
name = gets.chomp
symbols = {
:ac => "Ac",
:al => "Al",
:am => "Am",
:br => "Br",
:ba => "Ba",
:cr => "Cr"
}
if name.include? symbols
symbols.each{ |key, value| name.gsub!(key, value) }
end
puts name
我收到以下错误:
breakingbad.rb:15:in `include?': no implicit conversion of Hash into String (TypeError)
from breakingbad.rb:15:in `<main>'
答案 0 :(得分:3)
使用String作为哈希键。 String#gsub也接受Hash作为第二个参数。
如果第二个参数是Hash,匹配的文本就是其中一个 键,相应的值是替换字符串。
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