Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.5k 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...