From: Robert Klemme Date: 2010-05-16T05:50:20+09:00 Subject: Re: class best way for getters ? On 05/15/2010 04:42 PM, Une Bévue wrote: > i have a class "HFSFile" initialized by a parsed string > after initialization i get a Hash @attr with keys like :name, > :creation_date etc... > > what is the best way to write a getter for each individual key ? > > the obvious would be for example : > > def name > @attr[:name] > end > > or does exist a more clever way to get all of those getters ? > (same name for the getter that the key symbol) You can use this: irb(main):017:0> o = Object.new => # irb(main):018:0> ha.each {|k,| class< {:foo=>2, :bar=>3} irb(main):019:0> o.foo => nil irb(main):020:0> o.bar => nil irb(main):021:0> Or define method_missing to fetch data from the Hash. def method_missing(s,*a,&b) if a.empty? && @attr.has_key? s @attr[s] else super end end I would not do it though as it is not too fast. > another way : > > def [a_key] > return nil unless @attr.keys.include?(a_key) > return @attr[a_key] > end > > something like that ? You could use OpenStruct irb(main):001:0> require 'ostruct' => true irb(main):002:0> ha = {:foo => 2, :bar => 3} => {:foo=>2, :bar=>3} irb(main):003:0> os = OpenStruct.new(ha) => # irb(main):004:0> os.foo => 2 irb(main):005:0> os.bar => 3 irb(main):006:0> But the question remains, whether this is a good idea. Think about it: either you do not know keys beforehand. Then you can only use generic algorithms (i.e. query all keys and print their values). Or you do know keys beforehand and then you want to explicitly access individual keys (e.g. obj.name). If you know the names you can use Struct, e.g. irb(main):011:0> St = Struct.new :foo, :bar => St irb(main):012:0> s = St[*S.members.map{|m| ha[m]}] => # irb(main):013:0> s.foo => 2 irb(main):014:0> s.bar => 3 irb(main):015:0> Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/