简体   繁体   English

如何在Ruby中访问模块变量

[英]how to access module variables in ruby

I'm new to ruby so I apologize for the noob question and thanks for the help. 我是红宝石的新手,因此对菜鸟的问题深表歉意,并感谢您的帮助。 in ruby lets say I have a module like this: 在ruby中,可以说我有一个像这样的模块:

module foo 
 a = 1
 b = 2
end 

else in the code I have an object bar with a variable foo_id attached to it. 否则在代码中,我有一个对象栏,其中附加了变量foo_id。

is there an easy way to get 'a' or 'b' from the foo_id off the object bar? 有没有一种简单的方法可以从对象栏的foo_id中获取“ a”或“ b”? for example, doing something like this: 例如,执行以下操作:

foo.get(bar.foo_id) #--> returning 'a'

The only idea that really comes to mind for me is making a get method in the module, is there a smarter ruby way of doing this? 我真正想到的唯一想法是在模块中创建一个get方法,是否有更聪明的方法来实现呢? Thanks! 谢谢!

You can make a simple hash: 您可以进行简单的哈希处理:

module Foo
  IDS = {1 => 'a', 2 => 'b'}
end

And then access it: 然后访问它:

Foo::IDS[bar.foo_id]

Something along these lines should do the trick 遵循这些思路可以解决问题

module Foo
  IDS = {1 => 'a', 2 => 'b'}
end

puts Foo::IDS[1] #=> a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM