Victor Souza Victor Souza - 1 month ago 8
Ruby Question

Use argument ruby as a hash key

I want to create a code to name organic chemestry compounds. How can I use the arguments (num, bond) as keys for the hash? Ignore what I did to global variables, it's just to have a general idea of what I intent to do.

class Molecule
def molecule_name(num, bond)
@num = { 1 => 'met', 2 => 'et', 3=> 'prop', 4 => 'but'}
@bond = {1 => 'ano', 2 => 'eno', 3 => 'ino'}
end
a = Molecule.new; a = a.molecule_name(2,1)
print a
end

Answer

The question is a little unclear, but I think this is roughly what you're trying to achieve:

class Molecule
  def initialize(num, bond)
    @num = num
    @bond = bond
  end

  NAMES = {1 => 'met', 2 => 'et', 3 => 'prop', 4 => 'but'}
  BONDS = {1 => 'ano', 2 => 'eno', 3 => 'ino'}

  def molecule_name
    [ NAMES[@num], BONDS[@bond] ]
  end
end

a = Molecule.new(2, 1)
a.molecule_name # => ["et", "ano"]
Comments