1) 哈希没有 join() 方法。
2) 显然您发布的代码在一个类中,因此另一种解决方案是为您创建的名为@menus 的类实例变量提供一个访问器方法,然后您可以编写self.class.menus 而不是编写@menus:
class SomeClass
#Inside here and outside of any def's self=SomeClass
class <<self #Open the class's singleton class
attr_reader :menus
end
@menus = { Yay: '/', Yay2: '/yay2' } #@menus attaches to self, which is SomeClass
@menus.each do |title, link| #@menus is retrieved from whatever object self is, which is SomeClass
puts title, link
end
def foo
#Inside here self=the instance of SomeClass that called this method,
#so @menus will be retrieved from that instance--not SomeClass
'test ' + self.class.menus.keys.join(', ')
end
end
实例变量,即那些以@ 开头的变量,将它们自己附加到任何self 上,或者从任何self 中检索到。