Friday, May 18, 2012

Difference between Struck and OpenStruct

Ruby has two structure classes - Struct and OpenStruct.

Struct

This is the normal struct.
  • Generated struct is dealt as constant.
  • Accessor methods are not dynamic.
[1] pry(main)> Foo = Struct.new('Foo', :bar, :baz)
=> Struct::Foo
[2] pry(main)> foo = Foo.new(1, 2)
=> #<struct Struct::Foo bar=1, baz=2>
[3] pry(main)> foo.bar = 3
=> 3
[4] pry(main)> foo
=> #<struct Struct::Foo bar=3, baz=2>
[5] pry(main)> foo.qux = 4
NoMethodError: undefined method `qux=' for #<struct Struct::Foo bar=3, baz=2>
from (pry):5:in `<main>'

OpenStruct

This is dynamic struct.
  • Generated struct is dealt as variable.
  • Accessor methods are dynamic.
[1] pry(main)> require 'ostruct'
=> false
[2] pry(main)> foo = OpenStruct.new(bar:1,baz:2)
=> #<OpenStruct bar=1, baz=2>
[3] pry(main)> foo.bar = 3
=> 3
[4] pry(main)> foo
=> #<OpenStruct bar=3, baz=2>
[5] pry(main)> foo.qux = 4
=> 4
[6] pry(main)> foo
=> #<OpenStruct bar=3, baz=2, qux=4>

No comments:

Post a Comment