Hi,
I was learning Ruby's standard library `OpenStruct`. And doing so,out of
curiosity wrote the below code:
require 'ostruct'
person = OpenStruct.new
person.name = "John Smith"
person.age = 70
person.pension = 300
p person.instance_variables #=> [:@table, :@modifiable]
Now my question is - Where the above 2 instance variables have been
defined? What are their uses.
On the same not I also not able to understand the method `#modifiable`.
(Class: OpenStruct (Ruby 2.0.0)).
Can any one help me to understand the same?
You might be able to help yourself by using a tool like pry http://pryrepl.org to look at the variables and source. For example
ratdog:~ mike$ pry
[1] pry(main)> require 'ostruct'
=> false
[2] pry(main)>
[3] pry(main)> person = OpenStruct.new
=> #<OpenStruct>
[4] pry(main)> person.name = "John Smith"
=> "John Smith"
[5] pry(main)> person.age = 70
=> 70
[6] pry(main)> person.pension = 300
=> 300
[7] pry(main)> person
=> #<OpenStruct name="John Smith", age=70, pension=300>
[8] pry(main)> cd person
[9] pry(#<OpenStruct>):1> $ to_s
Owner: OpenStruct
Visibility: public
Number of lines: 21
def inspect
str = "#<#{self.class}"
ids = (Thread.current[InspectKey] ||= )
if ids.include?(object_id)
return str << ' ...>'
end
ids << object_id
begin
first = true
for k,v in @table
str << "," unless first
first = false
str << " #{k}=#{v.inspect}"
end
return str << '>'
ensure
ids.pop
end
end
I have found pry and its add-ons to be very useful for exploring bits of ruby code.
Mike
···
On 2013-05-24, at 6:44 AM, Love U Ruby <lists@ruby-forum.com> wrote:
From: /Users/mike/.rbenv/versions/2.0.0-p0/lib/ruby/2.0.0/ostruct.rb @ line 232:
--
Mike Stok <mike@stok.ca>
http://www.stok.ca/~mike/
The "`Stok' disclaimers" apply.