You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+46-4Lines changed: 46 additions & 4 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,8 +1,6 @@
1
1
# OpenStruct
2
2
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.
6
4
7
5
## Installation
8
6
@@ -22,7 +20,51 @@ Or install it yourself as:
22
20
23
21
## Usage
24
22
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")
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.
0 commit comments