Suppose you had some code like this: you have a hash that you want to add data to throughout your game.
module TH @@myData = {} def self.add_data(key, val) @@myData[key] ||= [] @@myData[key].push(val) end def self.myData @@myData endendTH.add_data(2, 3)p TH.myDataWhich is perfectly sensible if each key in your hash points to an array, but the keys are dynamically inserted into the hash so you are not guaranteed that the key you want actually exists.However, Ruby hashes are pretty nice.
You can declare it like this
module TH @@myData = Hash.new {|hash, key| hash[key] = [] } def self.add_data(key, val) @@myData[key].push(val) end def self.myData @@myData endendTH.add_data(2, 3)p TH.myDataAnd now whenever you try to access a key that is not in the hash, it will automatically run the code in that block (in this case, set it to empty array).This saves you from having to write ugly things like the explicit initialization code from the first example.
module TH @@myData = {} def self.add_data(key, val) @@myData[key] ||= [] @@myData[key].push(val) end def self.myData @@myData endendTH.add_data(2, 3)p TH.myDataWhich is perfectly sensible if each key in your hash points to an array, but the keys are dynamically inserted into the hash so you are not guaranteed that the key you want actually exists.However, Ruby hashes are pretty nice.
You can declare it like this
module TH @@myData = Hash.new {|hash, key| hash[key] = [] } def self.add_data(key, val) @@myData[key].push(val) end def self.myData @@myData endendTH.add_data(2, 3)p TH.myDataAnd now whenever you try to access a key that is not in the hash, it will automatically run the code in that block (in this case, set it to empty array).This saves you from having to write ugly things like the explicit initialization code from the first example.
Last edited by a moderator:
