对不起,如果它如此明显,我在红宝石上是一个非常棒的人(实际上,编码一般)。此代码用于命名化合物,但在我添加" funcao_organica"方法,我得到了这个输出:
main.rb:27:语法错误,意外的输入结束,期待keyword_end
我想我已经设定了所有的结局'在好地方。这个脚本有什么问题?
class Molecule
carbon_number_name = { 1 => 'met', 2 => 'et', 3=> 'prop', 4 => 'but', 5 =>'pent', 6 =>'hex'}; 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
elsif hidrogen == 2*(carbon_numbers) - 2
return 3
else
puts 'this molecule does not exist'
end
def funcao_organica(carbon_main_chain, oxigen)
@carbon_main_chain = carbon_main_chain
@oxigen = oxigen
if hidrogen == (2*(carbon_numbers) + (carbon_main_chain) - 1) && carbon_numbers > 2
print 'ol'
end
end
c = 5 ; h = 14 ; r = 5; o = 1
puts carbon_number_name[c] + bonds[x.molecule(h,c)] + x.funcao_organica(r,o)
end
答案 0 :(得分:3)
分子方法中缺少end
。结束if语句应该是end
:
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
elsif hidrogen == 2*(carbon_numbers) - 2
return 3
else
puts 'this molecule does not exist'
end #closing the if statement
end
答案 1 :(得分:1)
您必须拥有end
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
elsif hidrogen == 2*(carbon_numbers) - 2
return 3
else
puts 'this molecule does not exist'
end # <<<=== HERE
end
最后一个end
正在关闭方法定义。您还需要另一个end
来关闭if
。
答案 2 :(得分:1)
这里的一个大问题是你的特殊编码风格,尤其是不必要的编码风格
使用;
将多条线组合在一起并形成不规则的缩进
在代码中使用。保持简单,干净,有序,避免制作
基本语法错误。作为一个突破,错误在视觉上应该是显而易见的
通常的模式。
以下是您的代码的重构版本:
class Molecule
# Define CONSTANT values for those things that are used more than once
# within various methods inside your class.
CARBON_NUMBER_NAME = {
1 => 'met',
2 => 'et',
3=> 'prop',
4 => 'but',
5 => 'pent',
6 => 'hex'
}
BONDS = {
1 => 'ano',
2 => 'eno',
3 => 'ino'
}
ELEMENT = {
c: 5,
h: 14,
r: 5,
o: 1
}
def molecule(hydrogen, carbon_numbers)
@carbon_numbers = carbon_numbers
@hydrogen = hydrogen
case hydrogen
when 2*(carbon_numbers)
2
when 2*(carbon_numbers) + 2
1
when 2*(carbon_numbers) - 2
3
else
# Raise an error if one occurs, don't just print something.
raise 'this molecule does not exist'
end
end
def funcao_organica(carbon_main_chain, oxigen)
# NOTE: carbon_numbers needs to be defined here, but it isn't,
# and @carbon_numbers is only defined if molecule() is
# called previously. This could be an issue.
@carbon_main_chain = carbon_main_chain
@oxigen = oxigen
if hydrogen == (2*(carbon_numbers) + (carbon_main_chain) - 1) && carbon_numbers > 2
print 'ol'
end
end
end
# Move code outside the body of the class definition
x = Molecule.new
puts Molecule::CARBON_NUMBER_NAME[ELEMENT[:c]] + Molecule::BONDS[x.molecule(ELEMENT[:h],ELEMENT[:c])] + x.funcao_organica(ELEMENT[:r],ELEMENT[:o])