user4375076
user4375076

Reputation: 21

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:

module foo 
 a = 1
 b = 2
end 

else in the code I have an object bar with a variable foo_id attached to it.

is there an easy way to get 'a' or 'b' from the foo_id off the object bar? 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? Thanks!

Upvotes: 0

Views: 717

Answers (2)

emi
emi

Reputation: 2950

Something along these lines should do the trick

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

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

Upvotes: 0

August
August

Reputation: 12558

You can make a simple hash:

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

And then access it:

Foo::IDS[bar.foo_id]

Upvotes: 1

Related Questions