Created
November 16, 2009 22:33
-
-
Save santosh79/236384 to your computer and use it in GitHub Desktop.
This snippet shows how to create accessors in ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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