Tough to debug. Variables work in irb but the method fails
I discovered a bug that without a trailing number [0-9], my method will fail. Therefore I used a quick gsub to insert that number.
I'm working with this method:
def initialize(speciate)
y = speciate.gsub(/$/, '1')
x = y.scan(/[A-za-z]*\d+/)
@chem_species = x.map { |chem| chem.scan(/[A-Z][^A-Z]*/) }.flatten
end
When I test the variables in irb: (It works)
ruby-head > speciate = "NaCl"
=> "NaCl"
ruby-head > y = speciate.gsub(/$/, '1')
=> "NaCl1"
ruby-head > x开发者_开发技巧 = y.scan(/[A-za-z]*\d+/)
=> ["NaCl1"]
ruby-head > @chem_species = x.map { |chem| chem.scan(/[A-Z][^A-Z]*/) }.flatten
=> ["Na", "Cl1"]
When I run the Method in irb: (It fails)
ruby-head > x = Chemical.new("NaCl")
=> #<Chemical:0x0000010084d0b8 @chem_species=[]>
x = Chemical.new("H2SO4")
=> #<Chemical:0x000001008467e0 @chem_species=["H2", "S", "O4"]>
Thank you in Advance!
Since chemical symbols are always one uppercase letter, followed by zero or more lowercase letters, why not:
molecule = 'NaCl'
molecule.scan(/[A-Z][a-z]*[0-9]*/)
=> ["Na", "Cl"]
molecule = 'H2SO4'
molecule.scan(/[A-Z][a-z]*[0-9]*/)
=> ["H2", "S", "O4"]
molecule = 'Na2S'
molecule.scan(/[A-Z][a-z]*[0-9]*/)
=> ["Na2", "S"]
molecule = 'H'
molecule.scan(/[A-Z][a-z]*[0-9]*/)
=> ["H"]
精彩评论