我想创建一个代码来命名有机化学合成物。如何使用参数(num,bond)作为哈希的键?忽略我对全局变量的所作所为,只是对我想要做的事情有一个大概的了解。
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
答案 0 :(得分:1)
问题有点不清楚,但我认为这大致是你想要实现的目标:
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"]
答案 1 :(得分:0)
我尝试尽可能少地修改并仍然得到一个有效的例子:
for k in keys[:-1]:
if k not in d:
d[k] = {}
d = d[k]
这个例子有点像Ruby-ish:
class Molecule
attr_reader :num, :bond
def to_s
"#{@num}, #{@bond}"
end
def molecule_name(num, bond)
@num = { 1 => 'met', 2 => 'et', 3=> 'prop', 4 => 'but'}[num]
@bond = {1 => 'ano', 2 => 'eno', 3 => 'ino'}[bond]
end
end
a = Molecule.new
a.molecule_name(2,1)
puts a
#=> et, ano
puts a.num
#=>et
puts a.bond
#=>ano