I’m trying to iterate through an array, @chem_species = ["H2", "S", "O4"] and multiply a constant times the amount of constants present: H = 1.01 * 2, S = 32.1 * 1 and so on. The constants are of course defined within the class, before the instance method.
The code I’ve constructed to do this does not function:
def fw
x = @chem_species.map { |chem| chem.scan(/[A-Z]/)}
y = @chem_species.map { |chem| chem.scan({/\d+/)}
@mm = x[0] * y[0]
end
yields -> TypeError: can't convert Array into Integer
Any suggestions on how to better code this? Thank you for your insight in advance.
How about doing it all in one scan & map? The
String#scanmethod always returns an array of the strings it matched. Look at this:So just apply that to all of your
@chem_speciesusingmap:OK, now map over
@chem_species, converting each element symbol to the value of its constant, and each coefficient to an integer:There’s your molar masses!
By the way, I suggest you look up the molar masses in a single hash constant instead of multiple constants for each element. Like this:
Then that last map would go like: