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 >"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 >"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 >
=> "Shiva"
1.9.2p290 :008 >
=> "[email protected]"

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

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

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

1.9.2p290 :025 >,:email)
=> #<Class:0x000001008cae78>

, , , , ,

Leave a Reply

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