Hal Fulton wrote: > Just thought I'd share a little concept that I find > useful. Your comments are welcome. > > Sometimes objects are created with certain defaults. > One way to override them is with default values in > the constructor (and often corresponding writer methods). > > But sometimes I "don't like" the default and want to > change it (for this program/session). > > Often I use class-level accessors for that purpose. > > Here's a contrived example... > > > Cheers, > Hal > > > class Text > > class << self > attr_accessor :color > Text.color = "black" > end > > attr_accessor :color > > def initialize(txt, color="black") > # Hint: You can improve this further by saying > # def initialize(txt, color=Text.color) > puts "#{color} text..." > end > end > > > # The old way... > > a = Text.new("some") # black > b = Text.new("random","blue") # blue > c = Text.new("text") # black > c.color = "blue" # but now it's blue > > # The new way... > > Text.color = "blue" > > e = Text.new("Ruby is cool") # blue > f = Text.new("as dry ice") # blue Thinking in code - some other approach: def hash_replace(hash, replacement) tmp = hash.dup begin hash.update replacement return yield ensure hash.clear hash.update tmp end end >> class Test >> DEFAULTS = {:foo => "bar", 1 => 2} >> end => {1=>2, :foo=>"bar"} >> p Test::DEFAULTS {1=>2, :foo=>"bar"} => nil >> hash_replace( Test::DEFAULTS, {:foo => "replaced"} ) do ?> p Test::DEFAULTS >> end {1=>2, :foo=>"replaced"} => nil >> p Test::DEFAULTS {1=>2, :foo=>"bar"} => nil Hm... Kind regards robert