SlideShare a Scribd company logo
1 of 14
Download to read offline
Ruby’s Struct Class
                          typdef struct { int id; char *name; } Awesome;




                                     Ken Collins
                                    metaskills.net



Monday, November 14, 11
A Struct is a convenient way to
                   bundle a number of attributes
                      together, using accessor
                    methods, without having to
                       write an explicit class.




Monday, November 14, 11
Ad Hoc Example
           Language = Struct.new(:name, :class_based)

           ruby = Language.new "Ruby", true
           js   = Language.new "JavaScript", false
           objc = Language.new "Objective-C"

           ruby # => #<struct Language name="Ruby", class_based=true>
           js   # => #<struct Language name="JavaScript", class_based=false>

           ruby.class_based # => true
           js.class_based   # => false

           objc.class_based = true
           objc.class_based # => true




Monday, November 14, 11
Sub Class Example

          class MyObject < Struct.new(:id, :name, :key)

          end

          o = MyObject.new # => #<struct MyObject id=nil, name=nil, key=nil>

          o.id            # => nil
          o.name          # => nil

          o.id   = 12345
          o.name = "Test Object"

          o # => #<struct MyObject id=12345, name="Test Object", key=nil>




Monday, November 14, 11
But Why Structs?
                          class MyObject

                           attr_accessor :id, :name, :key

                           def initialize(*args)
                             @id, @name, @key = args
                           end

                          end

                          o = MyObject.new 12345, "Test Object"

                          o.id     # => 12345
                          o.name   # => "Test Object"




Monday, November 14, 11
But Why Structs?




Monday, November 14, 11
But Why Structs?
                          Convenient Alternative.




Monday, November 14, 11
But Why Structs?
                          Convenient Alternative.
                          Attribute Methods With [] & []=
                          Can Be Powerful. Not ivar based.




Monday, November 14, 11
But Why Structs?
                          Convenient Alternative.
                          Attribute Methods With [] & []=
                          Can Be Powerful. Not ivar based.
                          Easy Enumeration Of Attribute Data.




Monday, November 14, 11
But Why Structs?
                          Convenient Alternative.
                          Attribute Methods With [] & []=
                          Can Be Powerful. Not ivar based.
                          Easy Enumeration Of Attribute Data.
                          Default Equality On All Attributes.




Monday, November 14, 11
Attribute Accessors
                      class Person < Struct.new(:name)

                          def name
                            parts = self[:name].to_s.split(' ')
                            capped_parts = parts.map { |x| x.capitalize }
                            capped_parts.join(' ')
                          end

                      end

                      p = Person.new "KEN coLLins"
                      p.name    # => "Ken Collins"
                      p[:name] = 'mETAskiLLs'
                      p.name    # => "Metaskills"




Monday, November 14, 11
Easy Enumeration
            Customer = Struct.new(:name, :address, :zip)

            joe = Customer.new("Joe Smith", "123 Maple, Anytown NC",
            12345)

            joe.each { |x| x }
            # >> Joe Smith
            # >> 123 Maple, Anytown NC
            # >> 12345

            joe.each_pair { |name, value| puts("#{name} => #{value}") }
            # >> name => Joe Smith
            # >> address => 123 Maple, Anytown NC
            # >> zip => 12345




Monday, November 14, 11
Default Attribute Equality

           Customer = Struct.new(:name, :address, :zip)

           joe   = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
           joejr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
           jane = Customer.new("Jane Doe", "456 Elm, Anytown NC", 12345)

           joe == joejr      #=> true
           joe == jane       #=> false




Monday, November 14, 11
Thanks!
                           Ken Collins
                          metaskills.net



Monday, November 14, 11

More Related Content

Similar to Ruby struct

Parser combinators
Parser combinatorsParser combinators
Parser combinatorslifecoder
 
Active Record Introduction - 3
Active Record Introduction - 3Active Record Introduction - 3
Active Record Introduction - 3Blazing Cloud
 
De vuelta al pasado con SQL y stored procedures
De vuelta al pasado con SQL y stored proceduresDe vuelta al pasado con SQL y stored procedures
De vuelta al pasado con SQL y stored proceduresNorman Clarke
 
Enterprise javascriptsession3
Enterprise javascriptsession3Enterprise javascriptsession3
Enterprise javascriptsession3Troy Miles
 
02 JavaScript Syntax
02 JavaScript Syntax02 JavaScript Syntax
02 JavaScript SyntaxYnon Perek
 
Javascript the Language of the Web
Javascript the Language of the WebJavascript the Language of the Web
Javascript the Language of the Webandersjanmyr
 

Similar to Ruby struct (7)

Parser combinators
Parser combinatorsParser combinators
Parser combinators
 
Active Record Introduction - 3
Active Record Introduction - 3Active Record Introduction - 3
Active Record Introduction - 3
 
De vuelta al pasado con SQL y stored procedures
De vuelta al pasado con SQL y stored proceduresDe vuelta al pasado con SQL y stored procedures
De vuelta al pasado con SQL y stored procedures
 
Enterprise javascriptsession3
Enterprise javascriptsession3Enterprise javascriptsession3
Enterprise javascriptsession3
 
02 JavaScript Syntax
02 JavaScript Syntax02 JavaScript Syntax
02 JavaScript Syntax
 
Javascript the Language of the Web
Javascript the Language of the WebJavascript the Language of the Web
Javascript the Language of the Web
 
Immutability
ImmutabilityImmutability
Immutability
 

Recently uploaded

[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 

Recently uploaded (20)

[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 

Ruby struct

  • 1. Ruby’s Struct Class typdef struct { int id; char *name; } Awesome; Ken Collins metaskills.net Monday, November 14, 11
  • 2. A Struct is a convenient way to bundle a number of attributes together, using accessor methods, without having to write an explicit class. Monday, November 14, 11
  • 3. Ad Hoc Example Language = Struct.new(:name, :class_based) ruby = Language.new "Ruby", true js = Language.new "JavaScript", false objc = Language.new "Objective-C" ruby # => #<struct Language name="Ruby", class_based=true> js # => #<struct Language name="JavaScript", class_based=false> ruby.class_based # => true js.class_based # => false objc.class_based = true objc.class_based # => true Monday, November 14, 11
  • 4. Sub Class Example class MyObject < Struct.new(:id, :name, :key) end o = MyObject.new # => #<struct MyObject id=nil, name=nil, key=nil> o.id # => nil o.name # => nil o.id = 12345 o.name = "Test Object" o # => #<struct MyObject id=12345, name="Test Object", key=nil> Monday, November 14, 11
  • 5. But Why Structs? class MyObject attr_accessor :id, :name, :key def initialize(*args) @id, @name, @key = args end end o = MyObject.new 12345, "Test Object" o.id # => 12345 o.name # => "Test Object" Monday, November 14, 11
  • 6. But Why Structs? Monday, November 14, 11
  • 7. But Why Structs? Convenient Alternative. Monday, November 14, 11
  • 8. But Why Structs? Convenient Alternative. Attribute Methods With [] & []= Can Be Powerful. Not ivar based. Monday, November 14, 11
  • 9. But Why Structs? Convenient Alternative. Attribute Methods With [] & []= Can Be Powerful. Not ivar based. Easy Enumeration Of Attribute Data. Monday, November 14, 11
  • 10. But Why Structs? Convenient Alternative. Attribute Methods With [] & []= Can Be Powerful. Not ivar based. Easy Enumeration Of Attribute Data. Default Equality On All Attributes. Monday, November 14, 11
  • 11. Attribute Accessors class Person < Struct.new(:name) def name parts = self[:name].to_s.split(' ') capped_parts = parts.map { |x| x.capitalize } capped_parts.join(' ') end end p = Person.new "KEN coLLins" p.name # => "Ken Collins" p[:name] = 'mETAskiLLs' p.name # => "Metaskills" Monday, November 14, 11
  • 12. Easy Enumeration Customer = Struct.new(:name, :address, :zip) joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345) joe.each { |x| x } # >> Joe Smith # >> 123 Maple, Anytown NC # >> 12345 joe.each_pair { |name, value| puts("#{name} => #{value}") } # >> name => Joe Smith # >> address => 123 Maple, Anytown NC # >> zip => 12345 Monday, November 14, 11
  • 13. Default Attribute Equality Customer = Struct.new(:name, :address, :zip) joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345) joejr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345) jane = Customer.new("Jane Doe", "456 Elm, Anytown NC", 12345) joe == joejr #=> true joe == jane #=> false Monday, November 14, 11
  • 14. Thanks! Ken Collins metaskills.net Monday, November 14, 11