Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

best way to access a hash inside a Ruby module

I'm using a module to encapsulate a set of variables and methods related with those variables. One of these variables is a Hash that should be updated using module methods. I achieved this goal with the following code:

module MyModule
  @hash_a = {
        key1: "value1",
        key2: "value2"
  }
  def self.hash_a_set(key,value)
    @hash_a[key]=value
  end
  def self.hash_a_get(key)
    return @hash_a[key]
  end
end

MyModule.hash_a_get(:key1) # "value1" 
MyModule.hash_a_set(:key1,2) 
MyModule.hash_a_get(:key1) # 2 

Even tough this works, it does not feels right to use those setter and getter methods. Is there a way to access them as below (or any other way that resemble a hash syntax)?

MyModule.hash_a[:key1] # "value1" 
MyModule.hash_a[:key1]=2 
MyModule.hash_a[:key1] # 2 

Thanks


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you have a method hash_a that returns @hash_a then yes, the second form is trivial:

module MyModule
  @hash_a = {
        key1: "value1",
        key2: "value2"
  }
  def self.hash_a
    @hash_a
  end
end

Note that Ruby tries to steer away from having get and set methods, so if you can express this as something like x and x= then it usually works out better. In this case if exposing the Hash directly is acceptable, then just do the simplest thing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...