Guest User

Untitled

a guest
Jun 21st, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.51 KB | None | 0 0
  1. class Module
  2. # Take the name of a variable containing a hash and a list of keys
  3. # and define getter methods for those hash items
  4. # Keys need to be symbols or strings
  5. def hash_reader(hashvar, *keys)
  6. keys.each do |key|
  7. define_method(key) do
  8. hash = instance_variable_get hashvar
  9. hash[key]
  10. end
  11. end
  12. end
  13. end
  14.  
  15. class Foo
  16. hash_reader :@foo, :foo, :bar, :baz
  17.  
  18. def initialize(foo)
  19. @foo=foo
  20. end
  21. end
  22.  
  23. Foo.new(:foo => "bar", :bar => 42, :baz => 23).bar
  24. #=> 42
Add Comment
Please, Sign In to add comment