Shiva Kumar 's Blog

Start small,Think Big

Struct in Ruby

Struct is a simple way to create a class with number of attributes without explicitly creating a class

Syntax to create a class using struct

1.9.2p290 :004 > Struct.new("User",:name,:email)

Where User is the class name.Name and email are the attributes of the class where passing it on the fly.
So when you want to create new user all you do is

1.9.2p290 :006 > user=Struct::User.new("Shiva","[email protected]")
=> #<struct Struct::User name="Shiva", email="[email protected]">

This basically create a new user with name shiva and email
[email protected] order of passing the attribute is very important

1.9.2p290 :007 > user.name
=> "Shiva"
1.9.2p290 :008 > user.email
=> "[email protected]"

There is cool trick by Steve Klabnik to use struct .Using struct to inherit from

1.9.2p290 :012 > class User < Struct.new(:name,:email)
1.9.2p290 :013?> end
=> nil
1.9.2p290 :016 > user=User.new("shiva","[email protected]")
=> #<struct User name="shiva", email="[email protected]">
1.9.2p290 :017 > user.name
=> "shiva"

Because Struct.new(:name,:email) gives you class .And you can inherit it from like any other class

1.9.2p290 :025 > Struct.new(:name,:email)
=> #<Class:0x000001008cae78>

, , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *