Skip to content

Instantly share code, notes, and snippets.

@santosh79
Created November 16, 2009 22:33
Show Gist options
  • Save santosh79/236384 to your computer and use it in GitHub Desktop.
Save santosh79/236384 to your computer and use it in GitHub Desktop.
This snippet shows how to create accessors in ruby
module Accessor
def my_attr_accessor(*names)
names.each do |name|
ivar_name = "@#{name}"
define_method(name) do
instance_variable_get(ivar_name)
end
define_method("#{name}=") do |val|
$stderr.write "changing value of #{name} to #{val}"
instance_variable_set(ivar_name, val)
end
end
end
end
class Foo
extend Accessor
my_attr_accessor :val, :bar
#my_attr_accessor :bar
end
f = Foo.new
f.val = 99
puts "f's val is #{f.val}"
f.bar = 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment