1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-05 08:08:02 +00:00

Add Create Named Structs With Struct.new as a ruby til

This commit is contained in:
jbranchaud
2019-04-17 15:55:04 -05:00
parent 8209281e4d
commit 39efb39bbb
2 changed files with 40 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
For a steady stream of TILs from a variety of rocketeers, checkout
[til.hashrocket.com](https://til.hashrocket.com/).
_806 TILs and counting..._
_807 TILs and counting..._
---
@@ -614,6 +614,7 @@ _806 TILs and counting..._
- [Create an Array of Stringed Numbers](ruby/create-an-array-of-stringed-numbers.md)
- [Create A Hash From An Array Of Arrays](ruby/create-a-hash-from-an-array-of-arrays.md)
- [Create Listing Of All Middleman Pages](ruby/create-listing-of-all-middleman-pages.md)
- [Create Named Structs With Struct.new](ruby/create-named-structs-with-struct-new.md)
- [Create Thumbnail Image For A PDF](ruby/create-thumbnail-image-for-a-pdf.md)
- [Defaulting To Frozen String Literals](ruby/defaulting-to-frozen-string-literals.md)
- [Define A Custom RSpec Matcher](ruby/define-a-custom-rspec-matcher.md)

View File

@@ -0,0 +1,38 @@
# Create Named Structs With Struct.new
I often see `Struct` used to create some one-off anonymous data structure
like so:
```ruby
> person = Struct.new(:name, :age)
=> #<Class:0x007fc6c89112e8>
> person.new("Alice", 33)
=> #<struct name="Alice", age=33>
```
This will often get the job done, but on its own the resulting data
structure doesn't tell us as much as it could.
We can say more with a _named_ struct:
```ruby
Struct.new("Person", :name, :age)
=> Struct::Person
> Struct::Person.new("Bob", 24)
=> #<struct Struct::Person name="Bob", age=24>
```
When the first argument is a string that can be converted to a constant,
then we'll get a named struct that is subclassed under `Struct`.
We can also assign the struct initialization to a constant to do a similar
thing:
```ruby
> Person = Struct.new(:name, :age)
=> Person
> Person.new("Jerry", 45)
=> #<struct Person name="Jerry", age=45>
```
[source](https://ruby-doc.org/core-2.4.2/Struct.html#method-c-new)