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","")
=> #<struct Struct::User name="Shiva", email="">

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

1.9.2p290 :007 >
=> "Shiva"
1.9.2p290 :008 >
=> ""

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","")
=> #<struct User name="shiva", email="">
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 *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">