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

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
[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
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
[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
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

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