Created
October 17, 2012 19:06
-
-
Save rick/3907456 to your computer and use it in GitHub Desktop.
sample of how instance variables and accessors behave
This file contains hidden or 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
~ (master)(*)$ irb | |
>> | |
>> class Foo | |
>> attr_accessor :read_write | |
>> attr_reader :readonly | |
>> attr_writer :writeable | |
>> | |
?> def initialize(read_write, readonly, writeable) | |
>> @read_write = read_write | |
>> @readonly = readonly | |
>> @writeable = writeable | |
>> end | |
>> end | |
nil | |
>> foo = Foo.new(1, 2, 3) | |
#<Foo:0x7fe0831770d0 | |
attr_accessor :read_write = 1, | |
attr_reader :readonly = 2, | |
attr_writer :writeable = 3 | |
> | |
>> foo.read_write | |
1 | |
>> foo.readonly | |
2 | |
>> foo.writeable | |
NoMethodError: undefined method `writeable' for #<Foo:0x007fe0831770d0 @read_write=1, @readonly=2, @writeable=3> | |
from (irb):15 | |
from /opt/github/rbenv/versions/1.9.3-p194/bin/irb:12:in `<main>' | |
>> foo.writeable = 25 | |
25 | |
>> foo | |
#<Foo:0x7fe0831770d0 | |
attr_accessor :read_write = 1, | |
attr_reader :readonly = 2, | |
attr_writer :writeable = 25 | |
> | |
>> foo.readonly = 100 | |
NoMethodError: undefined method `readonly=' for #<Foo:0x007fe0831770d0 @read_write=1, @readonly=2, @writeable=25> | |
from (irb):18 | |
from /opt/github/rbenv/versions/1.9.3-p194/bin/irb:12:in `<main>' | |
>> foo.read_write = 1000 | |
1000 | |
>> foo | |
#<Foo:0x7fe0831770d0 | |
attr_accessor :read_write = 1000, | |
attr_reader :readonly = 2, | |
attr_writer :writeable = 25 | |
> | |
>> foo.instance_eval('@readonly = 25') | |
25 | |
>> foo | |
#<Foo:0x7fe0831770d0 | |
attr_accessor :read_write = 1000, | |
attr_reader :readonly = 25, | |
attr_writer :writeable = 25 | |
> | |
>> foo.instance_eval('@some_new_instance = 3000') | |
3000 | |
>> foo | |
#<Foo:0x7fe0831770d0 | |
@some_new_instance = 3000, | |
attr_accessor :read_write = 1000, | |
attr_reader :readonly = 25, | |
attr_writer :writeable = 25 | |
> | |
>> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment