Skip to content

Commit 06d37e6

Browse files
committed
README
1 parent 4cd1fc8 commit 06d37e6

File tree

1 file changed

+46
-4
lines changed

1 file changed

+46
-4
lines changed

README.md

Lines changed: 46 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
# OpenStruct
22

3-
Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/ostruct`. To experiment with that code, run `bin/console` for an interactive prompt.
4-
5-
TODO: Delete this and the text above, and describe your gem
3+
An OpenStruct is a data structure, similar to a Hash, that allows the definition of arbitrary attributes with their ccompanying values. This is accomplished by using Ruby's metaprogramming to define methods on the class itself.
64

75
## Installation
86

@@ -22,7 +20,51 @@ Or install it yourself as:
2220

2321
## Usage
2422

25-
TODO: Write usage instructions here
23+
```
24+
require "ostruct"
25+
26+
person = OpenStruct.new
27+
person.name = "John Smith"
28+
person.age = 70
29+
30+
person.name # => "John Smith"
31+
person.age # => 70
32+
person.address # => nil
33+
```
34+
35+
An OpenStruct employs a Hash internally to store the attributes and values and can even be initialized with one:
36+
37+
```
38+
australia = OpenStruct.new(:country => "Australia", :capital => "Canberra")
39+
# => #<OpenStruct country="Australia", capital="Canberra">
40+
```
41+
42+
Hash keys with spaces or characters that could normally not be used for method calls (e.g. <code>()[]*</code>) will not be immediately available on the OpenStruct object as a method for retrieval or assignment, but can still be reached through the Object#send method.
43+
44+
```
45+
measurements = OpenStruct.new("length (in inches)" => 24)
46+
measurements.send("length (in inches)") # => 24
47+
48+
message = OpenStruct.new(:queued? => true)
49+
message.queued? # => true
50+
message.send("queued?=", false)
51+
message.queued? # => false
52+
```
53+
54+
Removing the presence of an attribute requires the execution of the delete_field method as setting the property value to +nil+ will not remove the attribute.
55+
56+
```
57+
first_pet = OpenStruct.new(:name => "Rowdy", :owner => "John Smith")
58+
second_pet = OpenStruct.new(:name => "Rowdy")
59+
60+
first_pet.owner = nil
61+
first_pet # => #<OpenStruct name="Rowdy", owner=nil>
62+
first_pet == second_pet # => false
63+
64+
first_pet.delete_field(:owner)
65+
first_pet # => #<OpenStruct name="Rowdy">
66+
first_pet == second_pet # => true
67+
```
2668

2769
## Development
2870

0 commit comments

Comments
 (0)