Victor Souza Victor Souza - 1 month ago 6
Ruby Question

Method returns always the same result

I want to create a code to name organic chemestry compounds. There's the script I wrote below:

class Molecule
carbon_number_name = { 1 => 'met', 2 => 'et', 3=> 'prop', 4 => 'but'}; bonds = {1 => 'ano', 2 => 'eno', 3 => 'ino'}
x = Molecule.new
def molecule(hidrogen, carbon_numbers)
@carbon_numbers = carbon_numbers
@hidrogen = hidrogen
if hidrogen = 2*(carbon_numbers)
return 2
elsif hidrogen = 2*(carbon_numbers) + 2
return 1
else
return 3
end
end
puts carbon_number_name[carbon_numbers] + bonds[x.molecule(hidrogen,carbon_numbers)]


The method "molecule" isn't working as expected: its ever returning "2", despite of the conditions. Where is the mistake?

Answer

You are not comparing elements in your ifs statements, just assigning them to hidrogen.

To compare two objects use == method

Comments